-2

For example, I have this C code:

int len = 100;
int i;

// arr is pointer-to-pointer 2d array of char
char **arr = malloc(len * sizeof(char*));

for (i = 0; i < len; i++)
{
    // Allocate the sub-pointer
    arr[i] = malloc(len * sizeof(char));
    ...
}

...

// Is this part necessary?
for (i = 0; i < len; i++)
{
    // Freeing the sub-pointer
    free(arr[i]);
}

// Shrink the arr's size from 100 to 50
char** temp = realloc(arr, 50 * sizeof(char*));
...

Before to do realloc for arr to shrink its size (from 100 to 50), is it necessary to free the arr's sub-pointer?

for (i = 0; i < len; i++)
{
    free(arr[i]);
}
null
  • 8,669
  • 16
  • 68
  • 98
  • 2
    Why do you believe that it might be necessary? (Draw a diagram to convince yourself one way or the other.) – Oliver Charlesworth Jun 27 '15 at 14:08
  • 3
    Just read the `realloc` reference :/ – Imobilis Jun 27 '15 at 14:12
  • I'm calling `realloc` to shrink the size from 100 to 50, as you see the `arr` is pointer-to-pointer. By shrinking `arr` to smaller size (50), does the other 50 sub-pointers from `arr` are not needed to be freed? Does `realloc` will handle the free? – null Jun 27 '15 at 14:22

1 Answers1

3

Yes, you have to free all pointers if the reallocated array will have size that is less than the original size. For example

for (i = 50; i < len; i++)
{
    free(arr[i]);
}

char** temp = realloc(arr, 50 * sizeof(char*));

C does not have destructors so you have manually to free all objects pointed to by the removed elements. Otherwise there will be memory leaks.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • @Vlad you can't rely on that. But by the edit I can say it becomes a _possible_ duplicate: http://stackoverflow.com/questions/9575122/can-i-assume-that-calling-realloc-with-a-smaller-size-will-free-the-remainder – Imobilis Jun 27 '15 at 14:27
  • 1
    @iharob realloc does nothing with pointers stored in the allocated array. There will be memory lleaks. – Vlad from Moscow Jun 27 '15 at 14:28
  • Well that's just not true (: confront the C99 standard. – Imobilis Jun 27 '15 at 14:29
  • @VladfromMoscow Yes you are right I think, I was thinking of the pointer address and not about their pointees. – Iharob Al Asimi Jun 27 '15 at 14:30
  • (C99, 7.20.3.4p2) "The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size." >> C99 7.20.3.4 §4: The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object) – Imobilis Jun 27 '15 at 14:33
  • @Malina Please reread one more yourself the quote from the standard that to understand what objects it says about. – Vlad from Moscow Jun 27 '15 at 14:35