Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

memory

realloc

Can anyone summarize what is the correct usage of realloc()?

What do you do when realloc() fails?

From what I have seen so far, it seems that if realloc() fails, you have to free() old pointer. Is that true?

Here is an example:

   1.  char *ptr = malloc(sizeof(*ptr) * 50);
   2.  ...
   3.  char *new_ptr = realloc(ptr, sizeof(*new_ptr) * 60);
   4.  if (!new_ptr) {
   5.      free(ptr);
   6.      return NULL;
   7.  }

Suppose realloc() fails on line 3. Am I doing the right thing on line 5 by free()ing ptr?

like image 728
bodacydo Avatar asked Jul 25 '10 22:07

bodacydo


People also ask

What happens when realloc returns NULL?

If size is 0, the realloc() function returns NULL. If there is not enough storage to expand the block to the given size, the original block is unchanged and the realloc() function returns NULL. The storage to which the return value points is aligned for storage of any type of object.

What happens if realloc () fails?

If realloc() fails the original block is left untouched; it is not freed or moved.

What is realloc return error?

If realloc fails, it returns null pointer, but it doesn't deallocate the old memory.

What causes realloc to fail?

W.r.t failure realloc and malloc are almost equal. The only reason that realloc may fail additionally is that you give it a bad argument, that is memory that had not been allocated with malloc or realloc or that had previously been free d.


2 Answers

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.

like image 133
Gian Avatar answered Sep 28 '22 17:09

Gian


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.

like image 33
AnT Avatar answered Sep 28 '22 17:09

AnT