i want to check after calling malloc whether allocation is successful
or not. previously i have done like
ptr=malloc(size);
if(ptr==NULL)
But i came to know malloc can return valid pointer in case if argument
is zero.
Yes: Just like malloc(N), malloc(0) can return NULL or non-NULL.
Whichever it returns, though, you must not try to read or store through
that pointer. If it's NULL, well, you mustn't try to read or store
through NULL. If it's non-NULL you can read or store anything whose
size does not exceed the argument value, but since *every* C data type
is at least one byte wide there is nothing that fits in 0 bytes, hence
nothing you can safely store in 0 bytes.
To test for "success" of malloc(N), you could write
ptr = malloc(N);
if (ptr == NULL && N > 0) {
// failure
} else {
// "success"
}
I put "success" in quotes because of an ambiguity that is meaningless
in practice: If malloc(0) returns NULL, we cannot tell whether it
"succeeded" or "failed," but it really doesn't make any difference.
one solution is
if(size==0)
ptr=NULL;
else
ptr=malloc(size);
After this, a simple `if (ptr == NULL)' leaves you with the same
problem you had to begin with.
if you have any other suggestion please welcome.
One thing to keep in mind is that this `size' value comes from
somewhere, and will (presumably) govern what you later try to store
in the allocated area. If your program can calculate `size' as 0,
it should also never try to store more than 0 bytes in the allocated
area -- in which case, all will be well no matter what malloc(0)
returned.
Since a 0-byte memory area is mostly useless, you probably should
not be allocating a large number of them -- if you are, you've most
likely got a bug somewhere. Usually, 0-byte allocations arise when
you've got a data structure whose size you adjust up and down as the
circumstances require. Maybe you're keeping track of employees'
birthdays using 366 dynamically-allocated blocks, and the only person
born on February 29 quits: Your program might do
count[date] -= 1; // making it zero
Person *tmp = realloc(persons[date], count[date] * size *tmp);
if (tmp == NULL && count[date] > 0) {
// Can't delete: Hire him back again!
} else {
persons[date] = tmp;
}
In situations like this, a 0-byte allocation could be considered
"normal." But if you're routinely making thousands and thousands of
0-byte allocations, there's likely something wrong elsewhere.