Search code examples
cmemory-management

C Can I use data that I freed just after freeing it


I have a linked list node I want to code a function that frees node. But order to do that I have to update next variable of previous node. Can I access to previous_node->next (previous_node->next->next) just after freeing it?

struct node
{
   struct node *next;
}

void free_node(struct node *previous_node)
{
   free(previous_node->next);

   previous_node->next = previous_node->next->next; // can i do it or i have to store previous_node->next->next in a variable before freeing previous_node->next
}

I assembled it to see if there will be any diffrence but I saw my compiler to optimize it to how i write at up.


Solution

  • Can I use data that I freed just after freeing it

    No, that would exhibit undefined behavior.

    or i have to store previous_node->next->next in a variable before freeing previous_node->next

    Yes.