Reputation: 65
The following code in C is the beginning of a linked list project, where memory is allocated for a node (malloc), and values are assigned to the two struct members, i.e. data (int) and pointer to next node:
typedef struct nodeA NodeA;
struct nodeA{
int data;
NodeA* next;
};
void main(){
NodeA* test1 = (NodeA*) malloc(1 * sizeof(NodeA));
test1->next = (NodeA*) malloc(1 * sizeof(NodeA));
test1->data = 999;
printf("NODE: next=%p data=%d\n", test1->next, test1->data);
printf("NEXT: next=%p data=%d\n", test1->next->next, test1->next->data);
free(test1);
printf("FREE NODE: next=%p data=%d\n", test1->next, test1->data);
printf("FREE NEXT: next=%p data=%d\n", test1->next->next, test1->next->data);
}
The results of the two first printf() make sense.
However, after freeing the node (struct) pointer, the values of the members (of this node and of the next one) are modified:
NODE: next=0x563bd8335690 data=999
NEXT: next=(nil) data=0
FREE NODE: next=0x563bd8335010 data=0
FREE NEXT: next=(nil) data=1
Why is that so?
Especially, why does the data of the next node becomes 1, after the free(), instead of remaining 0?
Thanks a lot!
Edit: Thank you for your answers.
OK, using a freed pointer leads to an undefined behavior.
However, I observe that if you define "data" as a char* (instead of an int), then the last print generates a Segmentation fault.
Is there anything to understand about this, or is this just some random and meaning less behavior?
Upvotes: 1
Views: 113
Reputation: 385645
Dereferencing a freed pointer is undefined behaviour. Once you do this, all rules are out the window. It could work as expected, it could produce nonsense results, or it could crash. And how it behaves can change between runs. As such, it's useless to try to make sense of the program's behaviour.
Upvotes: 1