I have a struct which holds a next pointer to a struct of the same type.
I have the following code which stores the number of the struct that the node pointer stores, frees it, and sets node to the node->next. How is node->next known what it is if free has been called right before it?
double data = node->element;
free(node)
node = node->next;
return data;
However, following the same logic, the following code segfaults. The only difference is that this uses a node and the other just stores the element in its basic data type.
struct node *temp;
temp = node;
free(node);
node = node->next;
return temp;
Why is this happening? And how does the first segment of code work anyway?
Thanks
You shouldn’t ever dereference a freed pointer – it is asking for trouble and is likely the source of your segfault. Even if it doesn’t segfault, you cannot make any assumptions on the vailidity of the data at that memory address and so it is just not a good thing to do.
You haven’t given too many details in your question but why not modify your code slightly to try this order instead
this way you store the pointer before deleting
nodeand should not get a segfaultAs for the first code
why not just replace with
as this removes the code that accesses freed memory, and your line
is practically pointless when in the next line you free
nodeanyway.