Trying to take in several file names from the user at the command line and store them into a linked list, but I’m receiving a segmentation fault. The idea is to have the user enter each file name then enter ‘q’ when they’re finished.
I enter in the first file name, “man_on_moon.txt” and no error occurs. After I enter the second, “sat_moons_rings.txt” I get.. Segmentation fault: 11
I believe it’s occurring in my assignment to char *name, but am not sure.
char *name = malloc(sizeof(char) *50);
scanf("%s", name);
list *curr, *head;
curr = malloc(sizeof(list));
head = malloc(sizeof(head));
if(name != "q")
{
curr->item = name;
head->next = curr;
curr = curr->next;
scanf("%s", name);
}
while(name != "q")
{
curr->item = name;
curr = curr->next;
scanf("%s", name);
}
You never set
curr->nextto anything so it’s pointing toNULLthen you setcurrtocurr->next. Therefore when you get into the while loop you accesscurr->itemyou are trying to get the fields ofNULLand you get a segfault.The reason behind this is you are only mallocing space for 2 nodes. You have malloc space for every node you make.