I printed out a singly linked list with 1->2->3
. Then I tried to free the memory of head by using free(head);
, and I got 0->2->3
as the output.
I was wondering why the *next
of the head node still existed after free the memory. I thought there should be nothing left in the *head
when I passed to the print
function.
Sorry I am new to C and memory management. Please help me with some hints if possible.
#include <stdio.h>
#include <stdlib.h>
struct ListNode{
int val;
struct ListNode *next;
} ListNode;
void addNode(struct ListNode *head, int val);
void printNode(struct ListNode *head);
struct ListNode* deleteNode(struct ListNode* head, int val);
int main(int argc, char **argv){
struct ListNode* head;
head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
addNode(head, 2);
addNode(head, 3);
//test A: print the linked list value: 1 2 3
printNode(head);
printf("\n");
//test B: free memory : 0 2 3
struct ListNode* cur = head;
free(head);
printNode(head);
return 0;
}
void addNode(struct ListNode *head, int val){
struct ListNode* cur = head;
while(cur->next){
cur = cur->next;
}
struct ListNode* t;
t = (struct ListNode*)malloc(sizeof(struct ListNode));
t->val = val;
cur->next = t;
}
void printNode(struct ListNode *head){
struct ListNode* cur = head;
while(cur){
printf("%d ", cur->val);
cur = cur->next;
}
}