views:

144

answers:

4

Hi. I'm pretty sure I'm doing nothing wrong, but thought I'd ask anyway.

We have:

struct some_struct **array_of_ptrs = calloc (num, sizeof (struct some_struct*));

Now assume I just point each of these pointers in the 'array' to a struct some_struct. Now surely to free up the memory, I just do:

free (array_of_ptrs);

Surely this is perfectly acceptable? The reason I ask is because I am doing something similar in my code and gdb is complaining of a free error.

+2  A: 

This looks correct, as long as you realize that you're getting an array of pointers, not an array of structures, and you have to assign the pointers yourself. It sounds like that's what you're doing.

Also remember you can assign from array_of_ptrs[0] up to array_of_ptrs[num-1]. If you assign array_of_ptrs[num] you're in trouble.

Graeme Perrow
@graeme-perrow: Thanks Graeme, I just wanted some confirmation. There must be something else screwing up my code.
tamb
A: 

Yes, what you're doing here looks correct. You are allocating an array of num pointers. So, assuming a 4 byte pointer, 4 * num bytes, all initialized to zero. If you then assign them each to another pointer, that shoudln't create a problem when you free the pointer list.

What exactly is gdb complaining about? Could it be complaining about what these pointers are pointing to going unfreed? Freeing the pointer list will not free what they each point to, if the actual structs themselves were dynamically allocated.

Jeff Shattock
@jeff-shattock: Hi Jeff. I don't think it is complaining about what the pointers are pointing to, no. I'll try replicate it and post the error. Thanks.
tamb
A: 

If you do

free(array_of_ptrs);
then you are in affect creating a memory leak since each entry has a pointer in that array of pointers, it would be worth your while to do a
free(...);
on each pointer that you have malloc'd firstly, then issue the final
free(array_of_ptrs);
. This is quite a similar thing when dealing with a linked list using pointers

while (!*array_of_ptrs){
 struct *some_ptr_to_struct = *array_of_ptr;
 free(some_ptr_to_struct);
 *array_of_ptrs++;
}
free(array_of_ptrs);

Hope this helps, Best regards, Tom.

tommieb75
@tommieb75: But I don't malloc anything for these pointers in the array. They merely point to existing structs (which are dealt with later). So I don't see any 'point' in freeing each member of the array.
tamb
@tamb: oh, ok, when you said 'I just point each of these pointers in the 'array' to a *struct some_struct*.' I was under the impression that each pointer was malloc'd and pointing to the array of some_struct*. Sorry for the confusion.
tommieb75
A: 

Assuming all of the (struct somestruct *) pointers point to memory that's already been allocated, yes, it looks correct.

As for the error, what version of gcc are you using? I tested the code on 4.3.3 and it compiles with no complaints, even with -Wall -pedantic.

coledot