My question is regarding when using free() is appropriate in C. I’m using gcc 4.3.2.
Suppose, if had to deallocate a bunch of memory, in a linked list, the ideal way to go about it is(I’m guessing):
int freeLL(node *a)
{
if(a->next != NULL)
freeLL(a->next);
free(a);
return 0;
}
Now, suppose I were to do a similar thing on the following ADT:
A pointer “VertexNode” which has 2 more pointers: “Vertex” and “Edge”(say). Equivalent to saying:
struct vertexnode
{
vertex *v;
edge *e;
}
typedef struct vertexnode* VertexNode;
Later, when initializing an instance, I’ll do something like –
VertexNode V = malloc(sizeof(struct vertexnode));
V->v = malloc(sizeof(vertex));
So, ultimately while freeing: I used the same analogy as I used for the linked list.
free(V->v);
free(V);
This gave a runtime error, and when I commented out “free(V->v)”, the program worked fine.
My questions are:
a) Is simply doing free(V) sufficient? I mean, does free() work recursively on all pointers inside a given pointer?
b) If not, is there a memory leak in this case? And how do I ideally prevent that?
c) Lastly, is there a way I can keep track of how many bytes were allocated by malloc() and
how many of them were freed by free()?
I’m very sorry for the long question. Thank you in advance for your time and patience.
No, free does not work recursively, therefore you would indeed have memory leaks. The runtime error you are occuring is probably realated to a logic error (maybe
V->visNULLor you did not alloc it before freeing).If you are working with linux, using valgrind can help you profiling your program and mention leak errors. Compile using
cc *.c -ggdband then runvalgrind --leakcheck=full ./a.outwill output leak errors.