int main( )
{
int *p;
p=(int *)malloc(20);
printf("%u",p); \\ printing some memory adress
p=(int *)realloc(p,0);
printf("%u",p); \\ printing as 0
printf("%u",*p); \\ printing the value as 0
}
Now my question is the statement relloc working as the free() function as the pointer p is pointing to the NULL and NULL value in it. Will that 20 bytes be freed?
No, it may not be freed in all circumstances. C99 has this to say in
7.20.3.4 The realloc function:Now you may think that an allocation of zero bytes couldn’t possibly fail but the standard doesn’t mandate that. It says, for zero-sized objects:
So, if your implementation is one of those that doesn’t return NULL for a zero-size allocation, and it requires some housekeeping information for each allocation, and the memory arena is so full that you can’t store even another housekeeping header, and it’s not smart enough just to split the current allocation and return most of it to the arena, it may fail a zero-size
reallocand hence not free the original memory.Now this is a (very) edge case depending on a lot of decisions made in the implementation, most of which may seem bizarre to people with experience of writing them. Unfortunately, we have to allow for the edge cases as well 🙂
If it really worries you, I’d just change:
into:
A couple of other points.
/, not backslashes.pin that final line whether or not your implementation returns NULL for a zero-size allocation. See my second quote above where it states: “except that the returned pointer shall not be used to access an object”.malloc-type calls. This is a hangover from the dim dark past before C had avoid*, andmallocreturnedchar*. The problem with doing so nowadays is, if you forget to includestdlib.h, problems can be hidden from you.