Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The realloc() function deallocates the old object and returns a pointer to a new object of a specified size. If memory for the new object cannot be allocated, the realloc() function does not deallocate the old object and its value is unchanged. If the realloc() function returns NULL, failing to free the original memory will result in a memory leak. As a result, the following idiom is often recommended for reallocating memory:

Code Block
bgColor#FFcccc
size_t nsize;
/* initialize nsize */
char *p2;
char *p = (char *)malloc(100);
/* ... */
if ((p2 = (char *)realloc(p, nsize)) == NULL) {
  free(p);
  p = NULL;
  return NULL;
}
p = p2;

...

This compliant solution does not pass a size argument of zero to the realloc() function.

Code Block
bgColor#ccccff

size_t nsize;
/* initialize nsize */
char *p2;
char *p = (char *)malloc(100);
/* ... */

p2 = NULL;
if (nsize != 0) {
  p2 = (char *)realloc(p, nsize);
}
if (p2 == NULL) {
  free(p);
  p = NULL;
  return NULL;
}
p = p2;

...