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

Viewed 12191

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?

4 Answers
Related