I know that realloc
will free memory when necessary, and I know the third rule of C - "for every malloc
there must be an equal and opposite free
"... but how do these two work together?
The situation is best described in code:
int main()
{
myStruct **myStructArray;
int i, num_elements;
num_elements = getnumber(); // gets value for num_elements
myStructArray = (myStruct **) malloc(num_elements * sizeof(myStruct*));
for (i=0; i<num_elements; i++)
myStructArray[i] = (myStruct *) malloc(sizeof(myStruct));
// so far so good...
num_elements = getnumber(); // gets new, LOWER value
myStructArray = realloc(myStructArrary, num_elements * sizeof(myStruct*));
// rest_of_code, and necessary free loop for myStructArray etc...
}
Obviously the above is nothing more than a snippet, but a snippet paints a thousand words.
Would this create a memory leak? I know the call to realloc
will free the pointers' memory, but I can see arguments for and against the possibility that there is still going to be a bunch of memory forgotten about.
A leak can be circumvented by incorporating int number_elements_new
into the code and loop free
-ing the surplus myStruct
s before calling realloc
to free the (now NULL) pointers.
If realloc
does the donkeywork and frees up ALL the associated memory that's great, otherwise I've got to trawl through to make sure nothing has been missed - myStruct
itself contains allocated memory and so on.
Thank you for your recommendations...