Reputation: 11
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.
Upvotes: 1
Views: 475
Reputation: 2806
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
.
Upvotes: 0
Reputation: 34592
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.
Upvotes: 0
Reputation:
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.
Upvotes: 0
Reputation: 57288
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.
Upvotes: 2