I know i can change the code to fix the error but I don't understand why I am getting a segmentation fault. All help is appreciated, thank you.
typedef struct nodes{
int data;
struct nodes *next;
} node;
int main(int argc, char * argv[]){
node *head = NULL;
node *tmp = NULL;
int i;
head = malloc(sizeof(node));
tmp = head;
for(i = 0; i < 10; i++){
tmp->data = i;
tmp->next = malloc(sizeof(node));
tmp = tmp->next;
}
tmp = NULL;
for(tmp=head; tmp->next != NULL; tmp = tmp->next){
printf("%d\n", tmp->data);
}
}
This is the output:
0
1
2
3
4
5
6
7
8
9
0
Segmentation fault: 11
You'll get slightly cleaner code by building the list backwards. In other words, start by adding the last node to the list, and then insert additional nodes at the beginning of the list. The code looks like this:
node *head = NULL;
for (int i = 9; i >= 0; i--)
{
node *tmp = malloc(sizeof(node));
tmp->data = i;
tmp->next = head;
head = tmp;
}
Note that since head
is initially NULL
, the last node in the list will have its next
pointer set to NULL
. That's what was missing in your code.