Search code examples
cfreedynamic-memory-allocationrealloc

How to free pointers within a dynamic array when realloc fails?


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.


Solution

  • 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;
    }