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.

0

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

man the realloc,you'll see

If realloc() fails the original block is left untouched; it is  not  freed
or moved.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.