Hi everyone,
Just a quick background, i'm in my first year of university and have only doune maybe 6-7 weeks of C so try and keep things simple
I was trying to understand linked lists so was following the tutorial :
Cprogramming.com Tutorial: Linked Lists
Here is the code i am trying to get to work. I've just run it through GDB and the malloc line is the one giving me a problem. GDB output:Code:#include <stdio.h> #include <stdlib.h> struct node { char c; struct node *next;}; main() { struct node *root; // Root node of list struct node *linkptr; // Pointer to link the nodes; root = malloc(sizeof(struct node)); root -> next = 0; root -> c = 'L'; linkptr = root; while( linkptr != NULL ) { printf("%c\n",linkptr->c); //printf("in loop"); // scanf("%c",&(linkptr -> c)); linkptr = linkptr -> next; } /* Creates a list a node at the end of the list*/ //linkptr -> next = malloc(sizeof(struct node)); linkptr->next = malloc(sizeof(struct node)); // Remember linkptr -> next now points to null because we are at the last node in the list so it's ok to allocate a new area of mem to point to. linkptr = linkptr -> next; if (linkptr == 0) // checks to see if we are out of memory { printf("out of memory"); return(0); } linkptr -> next = 0; // Set the next pointer to NULL to indicate we are at the end of our list. linkptr -> c = 'E'; return(0); }
Program received signal SIGSEGV, Segmentation fault.
0x00000000004005ab in main () at ll1.c:29
If i change it to just 'linkptr' instead of 'linkptr -> next' then it works but will that not also overwrite linkptr->char that is stored?
I might be coming across as very confused so bear with me, the helpdesk guy doesn't know C so i'm pretty stuck at the moment.
Thanks