Dynamic arrays: using realloc() without memory leaks

If realloc() fails it returns NULL.

So if you do (and assuming realloc() would fail)

result = realloc(result, ...);

result will be assigned NULL and what it pointed to is not free()ed and the address to be free()ed is lost.

To fix this do:

{
  void * tmp = realloc(result, ...);
  if (NULL == tmp)
  {
    /* Handle error case, propably freeing what result is pointing to. */
  }
  else
  {
    result = tmp;
  }
}

Leave a Comment