Reputation: 2010
My question is simple I think. And yes, I am aware that there are several linked list/segmentation fault related questions on stack overflow, but I think those have to do with uninitialized pointers, whereas I think my issue is related to strings.
I have a linked list whose node structures consist of two variables: a link to the next
node and (!) a string
.
my question: how do I free the memory of the node (keeping in mind it was malloc
ated) without causing a segmentation fault by free()
ing the string?
While browsing the other questions related to free()
and strings
, I have come under the impression that it is not necessary to free()
them. But how does one free a struct
that has a string
nested string inside it?
The linked list functions I am implementing seem to be working except destroyList()
, which frees all allocated memory of the node passed to the function along with all subsequent nodes.
Here is the implemenation:
void destroyList(struct listNode *pNode){
if(pNode->next != null){
destroyList(pNode->next);
}
free(pNode);
}
and here is the listNode
structure:
struct listNode{
char addr[MAX_ADDR_LENGTH];
struct listNode *next;
};
Upvotes: 0
Views: 1495
Reputation: 131
Rule of thumb is use free() when you used malloc(). Strings do not need to be free()'d as free()'ing the node deallocates the memory allocated to whole structure which includes the memory for the string. And, why dont you use gdb or valgrind to debug where exactly the fault arises? In gdb, you can use options like where and print stacktrace to precisely locate where the segfault is occuring. It's a good investment to learn gdb now. This part of the code looks fine to me.
Upvotes: 1
Reputation: 20163
Your "string" (the char
buffer) is part of the list node struct. It doesn't get allocated separately from the nodes, so it doesn't need to be freed. Freeing the node is all you need to do.
Upvotes: 1
Reputation: 43188
You probably overran the stack.
Try this:
void destroyList(struct listNode *pNode){
while (pNode) {
struct listNode *x = pNode;
pNode = pNode->next;
free(x);
}
}
Of course it could be you passed in a bad pNode, in which case this won't fix.
Or you have corrupted the heap elsewhere.
Upvotes: 0
Reputation: 15055
Only something that has a malloc
(or similar) will need a free
.
For example, if you struct was like this:
struct listNode{
char *addr;
struct listNode *next;
};
Then you would allocate like this:
struct ListNode Node = malloc(sizeof(struct listNode));
Node.addr = malloc(size of the string);
And you would have to free the string before then freeing the node itself. Your string as part of the struct, with a fixed length and so there is no string to free.
Your issue, however, must be something else. Try to avoid recursion (i.e. your example uses recursion - on a big list this will cause a stack overflow) and nullify your pointers when freeing them, and check pointers (are non null) before using them.
Upvotes: 0