0

Possible Duplicate:
How to handle realloc when it fails due to memory?

Let's say I have an array of pointers

char **pointers_to_pChar = 0;
pointers_to_pChar = (char **)malloc(sizeof(char *) * SIZE);
for (i = 0; i < SIZE; ++i)
{
    pointers_to_pChar[i] = malloc(sizeof(char) * 100));
}

//some stuff...
//time to realloc 
pointers_to_pChar = realloc(pointers_to_pChar, sizeof(char *) * pointer_count + 1);
if (pointers_to_pChar == NULL)
{
    //i have to free pointers in the array but i don't have access to array anymore...
}

How should I handle the situation when realloc fails? I need to access each pointer within the array and free them in order to avoid a possible memory leak.

Community
  • 1
  • 1
Hayri Uğur Koltuk
  • 2,970
  • 4
  • 31
  • 60

3 Answers3

1

You should realloc to a different pointer first, then check for NULL.
This way you still have access to the array.

Minion91
  • 1,911
  • 12
  • 19
1

man the realloc,you'll see

If realloc() fails the original block is left untouched; it is  not  freed
or moved.
rpbear
  • 640
  • 7
  • 15
1

Write the result to a temporary pointer; if realloc fails, the original block of memory is left intact, but it returns a NULL, so you wind up losing your pointer to it:

char **tmp = realloc(pointers_to_pChar, ...);
if (!tmp)
{
  //realloc failed
}
else
{
  pointers_to_pChar = tmp;
}
John Bode
  • 119,563
  • 19
  • 122
  • 198