How will I free the nodes allocated in another function?
struct node {
int data;
struct node* next;
};
struct node* buildList()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
return head;
}
I call the buildList function in the main()
int main()
{
struct node* h = buildList();
printf("The second element is %d\n", h->next->data);
return 0;
}
I want to free head, second and third variables.
Thanks.
Update:
int main()
{
struct node* h = buildList();
printf("The element is %d\n", h->next->data); //prints 2
//free(h->next->next);
//free(h->next);
free(h);
// struct node* h1 = buildList();
printf("The element is %d\n", h->next->data); //print 2 ?? why?
return 0;
}
Both prints 2. Shouldn't calling free(h) remove h. If so why is that h->next->data available, if h is free. Ofcourse the 'second' node is not freed. But since head is removed, it should be able to reference the next element. What's the mistake here?
free()
with the returned value frommalloc()
. – Tooleyfree()
does not erase the content of the memory, it merely allows those contents to be reused later. The pointerh->next
remains valid as a coincidence because the memory youfree()
'd has not yet been reused. – Jermainejermanfree
the last node on your list, because if you free for exampleh
then you won't be able to geth->next
becauseh
won't exist, except if you use a temporary variable to holdh->next
and thenfree
h
. If you just wan tofree
these 3 nodes you could do:free(h->next->next)
which willfree
thethird
node, thenfree(h->next)
which willfree
second
node, and thenfree(h)
which willfree
thehead
node. But you CANNOTfree(h)
first because then you won't be able to dofree(h->next)
for the rest of your list nodes. – Majorsh->next->data
could get you a segmentation fault. Ok, let's say you haveh
having the following data:h->next = 0x12341281; h->data = 1
, when you dofree(h)
you just let know the machine that in a futuremalloc
you can overwriteh
, thath
is not more used by your program. But the datah->next = 0x12341281; h->data = 1
seem to keep existing, that doesn't mean you should use them. – Majorsmalloc
, whereh->next
andh->data
is saved, something else will be written. And then when doingh->next->data
will get you a segmentation fault. – Majors