I am currently learning lists, and I am trying to write a function that deallocates the memory. I tried, but even though it compiles, it returns a non-zero value. I don't understand why my program doesn't return 0 when I use the deallocating function in the main function. However,the program is executed successfully when I don't use the deallocating function. To me the function seems fine. I can't spot the error.
#include <stdio.h>
#include <stdlib.h>
typedef struct person {
int age;
struct person *next;
} person;
void insert_start(person **head, int x);
void insert_end(person **head, int x);
void insert_position(person **head, int x, int position);
void deallocating(person **head);
int main() {
person *head = NULL;
person p1 = { 2, NULL };
person p2 = { 3, NULL };
head = &p1;
p1.next = &p2;
insert_end(&head, 4);
insert_start(&head, 12);
insert_position(&head, 100, 3);
for (person *curr = head; curr != NULL; curr = curr->next) {
printf("%d\n", curr->age);
}
deallocate(&head);
return 0;
}
void insert_start(person **head, int x) {
person *nextnode = malloc(sizeof(person));
nextnode->age = x;
nextnode->next = *head;
*head = nextnode;
}
void insert_end(person **head, int x) {
person *nextnode = malloc(sizeof(person));
nextnode->age = x;
nextnode->next = NULL;
person *find = *head;
while (find->next != NULL) {
find = find->next;
}
find->next = nextnode;
}
void insert_position(person **head, int x, int position) {
person *nextnode = malloc(sizeof(person));
nextnode->age = x;
nextnode->next = NULL;
person *find = *head;
int curr = 1;
while (curr != position) {
find = find->next;
curr++;
}
nextnode->next = find->next;
find->next = nextnode;
}
void deallocate(person **head) {
person *curr = *head;
while (curr != NULL) {
person *del = curr;
curr = curr->next;
free(del);
}
*head = NULL;
}
It seems to me that in your deallocate function:
The first time del takes the value of curr, then you deallocate del, but del and curr are now the same. Then you use curr->next, but curr is no longer valid.