Reputation: 1
I keep getting a segmentaion fault when trying to create a simple linked list.The problem seems to occur inside the print_list function.I've been trying to fix this for about an hour but it's still not working.I'd really appreciate your help.This is the code:
#include<stdio.h>
#include<stdlib.h>
struct node{
double value;
struct node *next;
};
struct node* getnode()
{
struct node* create;
create=(struct node*)malloc(sizeof(struct node));
create->next=NULL;
return create;
}
void insert_at_beg(struct node*first,double x)
{
struct node*temp=getnode();
if(!first)
{
temp->value=x;
first=temp;
}
else
{
temp->value=x;
temp->next=first;
first=temp;
}
}
void print_list(struct node*first)
{
struct node*temp;
temp=first;
if(temp==NULL)
{ printf("The list is empty!\n");
return;
}
while(temp!=NULL)
if(temp->next ==NULL) // this is where i get the segmentation fault
{ printf("%lf ",temp->value);
break;
}
else
{
printf("%lf ",temp->value);
temp=temp->next;
}
printf("\n");
}
int main()
{
struct node *first;
insert_at_beg(first,10.2);
insert_at_beg(first,17.8);
print_list(first);
system("PAUSE");
}
Upvotes: 0
Views: 79
Reputation: 54
You can use gdb - [GNU debugger]. It should help you to figure out where exactly the segmentation fault is. You can find more information in this link
Upvotes: 1
Reputation: 400109
Make it return the new head of the list:
void insert_at_beg(struct node *first, double x)
{
struct node *temp = getnode();
temp->value = x;
temp->next = first;
return temp;
}
A bit simpler, too. :)
Then in main()
, do:
struct node *first = insert_at_beg(NULL, 10.2);
first = insert_at_beg(first, 17.8);
Upvotes: 1
Reputation: 3711
You have an invalid address from the temp->next call. C does not default initialize variables you need to to set the first value to NULL
struct node* first = NULL;
Upvotes: 0