Home > Mobile >  value inside a linked lists Node exists after change, why?
value inside a linked lists Node exists after change, why?

Time:08-21

lets say we have a linked list = [1] -> [2] -> [3] -> [4]

typedef struct Node
{
    int val;
    struct Node* next;
}Node;

I have the head and to free all the allocated memory I do

printf("%i", head->val); // prints 1

Node* tmp = head;
while(tmp != NULL)
{
    Node* tmp2 = tmp;
    tmp = tmp->next;
    free(tmp2);
}

printf("%i", head->val); // prints a big number, but exists and is not NULL

if (tmp == NULL)
{
    print("is null"); // this prints too
}

why head->val still exists and tmp doesn't? shouldn't head->val be NULL after freeing it ? I assumed since head is a pointer itself and i set it to another pointer then its pointing at the location anyway so when I free tmp it should free the thing in the address that head is pointing to aswell?

CodePudding user response:

As stated in comments, attempting to access member of head after freeing it invokes undefined behavior. head->val might be NULL, or it might still have a value because that memory has not been overwritten.

The point of undefined in "undefined behavior" is that we don't know and can't know for sure what will happen.

  • Related