Home > Mobile >  c programming linked list compiles but segfaults
c programming linked list compiles but segfaults

Time:11-24

code can be found here https://pastebin.com/DuxzjSsr

i compiled with gcc -g and run in gdb and it says the segfault happens at

while(current != NULL){
   current = current->next
}

i cant understand why, i copied the code from this link https://www.learn-c.org/en/Linked_lists for printing out a linked list etc and the code is pretty much the same as far as i can tell.

CodePudding user response:

In your code you never properly initialize next. So the value is to likely be "garbage" data leftover in memory. Here you create a clist variable and only set the data property:

  clist mylist;
  mylist.data = "First string";

The issue is you don't do mylist.next = NULL;, so whatever happened to be at that location is still there, and your code will attempt to assign that value to current in your list iteration, current = current->next. This may cause a segfault. You are attempting to access memory at an arbitrary location and the result is undefined behavior. As a rule of thumb, always initialize pointers or assign their value to NULL.

CodePudding user response:

First of all you initialize the head of the list wrong. Except of the data member, you should also initialize the next pointer so it does not point at some garbage value. When your print function reads that pointer(or any other function) it will crash.

Add this to your main

mylist.next = NULL;

Also the insertion of your data has the same mistake(line 34-35)

current->next = (clist *)malloc(sizeof(clist));
current->next->data = strtoadd;

This line will do the trick for data insertion

current->next->data->next = NULL;
  • Related