What is the correct usage of realloc() when it fails and returns NULL? What is the correct usage of realloc() when it fails and returns NULL? c c

What is the correct usage of realloc() when it fails and returns NULL?


From http://www.c-faq.com/malloc/realloc.html

If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated.

Therefore you would indeed need to free the previously allocated memory still.


It depends on what you want to do. When realloc fails, what is it you want to do: free the old block or keep it alive and unchanged? If you want to free it, then free it.

Keep in mind also, that in C89/90 if you make a realloc request with zero target size, realloc function may return a null pointer even though the original memory was successfully deallocated. This was a defect in C89/90, since there was no way to tell the success from failure on null return.

In C99 this defect was fixed and the strict relationship between null return and success/failure of reallocation was guaranteed. In C99 null return always means total failure of realloc.


If realloc fails I don't think you would want to delete the original block since you will lose it. It seems like realloc will resize the old block (or return a pointer to a new location) and on success will return a pointer to the old block (or new location) and on failure will return NULL. If it couldn't allocate a new block the old block is untouched.