johns4ta
johns4ta

Reputation: 896

Segmentation Fault when freeing singly linked list from memory

I am relatively new to the idea of pointers and C, so I apologize if this is a really simple problem. I am trying to free a singly linked list from memory that is created. The singly list is created fine, but I am having trouble free it from memory, I get a segmentation fault. Any ideas where I am going wrong? I need to have separate methods for both freelist and freenode. Avail is a global pointer variable and is part of the code that I'm sure works. The problem exists in free list and I'm just not sure where.

   void freelist(olnode **list) {
   olnode *ptr = *list;
    while (*list != NULL) {
     ptr = *list
     freenode(&ptr);
     ptr = ptr->next;
    }
   }

   void freenode(olnode **ptr) {
    if(*ptr != NULL) {
     (*ptr)->next = avail;
     avail = *ptr;
     *ptr = NULL:
    }
   }

Upvotes: 0

Views: 121

Answers (2)

Philipp
Philipp

Reputation: 69703

Freenode sets the pointer passed to it to NULL. Afterwards freelist tries to dereference the pointer which is now null. That's where the program crashes.

Besides that, your program doesn't really free any data. It just changes the pointers pointing to the data to point to NULL. That means the memory will stay allocated and isn't available for new data. To mark the memory a pointer points to as no longer needed, you need to call the free() method from the standard library on the pointer which points to it. Setting the pointer to NULL afterwards is not needed, but a good practice to make sure that any subsequent try to access the free'ed memory location results in a predictable crash and not in totally unpredictable behavior.

Upvotes: 3

Keith Randall
Keith Randall

Reputation: 23265

You need to grab the next pointer from the node before freeing it.

Not this:

 freenode(&ptr);
 ptr = ptr->next;

but this:

 olnode *next = ptr->next;
 freenode(&ptr);
 ptr = next;

Upvotes: 1

Related Questions