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

bodacydo picture bodacydo · Jul 26, 2010 · Viewed 10.9k times · Source

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?

Answer

Gian picture Gian · Jul 26, 2010

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.