Reputation: 5
When I'm running the following C program for linked list creation in gcc compiler in ubuntu 13.04, I'm getting a message of : Segmentation fault (core dumped) , after the list elements are input from the user , without proceeding further. Kindly help.
#include<stdio.h>
#include<stdlib.h>
int main()
{
/* creating a singly linked list,displaying its elements and finding the sum and average of its elements and searching a particular element in it */
typedef struct node
{
int info;
struct node *next;
}N;
N *ptr,*start,*prev;
int i,n,x;
ptr=NULL;
start=NULL;
prev=NULL;
printf("Enter the number of list elements: ");
scanf("%d",&n);
prev = (N*)malloc(sizeof(N));
start = (N*)malloc(sizeof(N));
for(i=0;i<n;i++)
{
ptr= (N*)malloc(sizeof(N));
prev->next = ptr;
printf("enter the %dth element\t\n",(i+1));
scanf("%d",&x);
ptr->info = x;
if(start==NULL)
{
start=ptr;
prev=ptr;
ptr->next = NULL;
}
else
{
prev=ptr;
}
} /* linked list created consisting of n nodes */
/* finding sum and average*/
int sum=0;
float avg;
ptr=start;
for(i=0;i<n;i++)
{
sum =sum + ptr->info;
ptr = ptr->next;
}
avg = (float)sum/n; /* summing and averaging completed */
/* displaying data */
ptr=start;
printf("\n The list elements are : ");
while(ptr != NULL)
printf("%d\t",ptr->info);
printf("\n");
printf("The sum of list elements is: %d",sum);
printf("The average of list elements is: %f",avg);
return 0;
}
Upvotes: 0
Views: 140
Reputation: 6070
when I strip your code I come to this Seltsamkeit:
start = (N*)malloc(sizeof(N));
for(i=0;i<n;i++) {
if(start==NULL)
start can never be NULL in this context
i normally use "head" and "next" for the pointer to the working memory, and "list" as a running pointer to the last element of the list for the really allocated memory-linked-list. the metacode is:
list = NULL;
head = NULL;
for (i = 0; i < n; i++) {
next = malloc();
if (head == NULL) {
head = next; // setting the first haed;
} else {
list->next = next; // attaching to the end
}
list = next; // pointing to the last element
}
Upvotes: 0
Reputation: 19706
Looks like you meant to do
start = NULL;
prev = NULL;
at the beginning, and also correct -
prev->next = ptr;
to
if (prev != NULL)
prev->next = ptr;
or move it to the else section (before prev = ptr).
This way, the first iteration would make start point to the first element, and the next ones would make the prev element point to the current ptr.
By the way, some linked lists hold a dummy "anchor" element for simpler maintenance, but in your case I see you expect the data to appear from the first element already.
Upvotes: 1