gowrath gowrath - 11 months ago 57
C Question

Does realloc() free old memory (when old memory might be pointers to other memory)?

Suppose I have a pointer p1 to an array (on the heap) of structs s1 where each struct s1 also has a pointer to another struct s2 (on the heap). If I call realloc() on p1 to resize it, will the old memory being held by the structs of the pre-realloced array be freed (the s2s on the heap)?

I'm fairly sure the answer to this question is no because the documentation states that

if the area pointed to was moved, a free(ptr) is done
which implies that it will only free up to one level deep. Is that correct? And if so, would the best solution be to manually malloc a new array, iterate over the old array, copy the values to the new larger array, and free the structs while at it?

Answer Source

realloc() only reallocates the top-level array you give it. As EOF mentioned in a comment, it doesn't know that the contents of the array are pointers, so it can't do anything to those elements.

If you're enlarging the array, you don't need to do anything with the arrays that it points to. Their memory is untouched, and the pointers will be copied from the old memory to the new memory allocated by realloc().

If you're shrinking the array, you need to make sure that you first free any of the arrays that were pointed to by the elements that are beyond the end of the result, to avoid leaking memory.