By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,336 Members | 2,307 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,336 IT Pros & Developers. It's quick & easy.

segmentation fault

P: 1
i got almost every time the segmentation error during running my programme.
why this error occur? how it can be removed?

i have a programme.......


#include<stdio.h>
#include<stdlib.h>
struct node
{
char name[10];
struct node *link;
};
void add (struct node **,char *);
void print(struct node *);
void main()
{
struct node *p;
int i,n;
char s[10];
printf("Enter no. of node, want to add :");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
printf("Enter name:");
gets(s);
add(&p,s);

}
print(p);

return ;
}
void add (struct node **q,char *t)
{
struct node *temp,*r;
int i,j;
temp=(struct node *)malloc(sizeof(struct node));
temp=*q;
if(*q==NULL)
{
*q=temp;
temp->link=NULL;
for(i=0;i<=9;i++)
{
(temp->name)[i]=*t;
t++;
}
}

else
{
while(temp->link!=NULL)
temp=temp->link;
r=(struct node *)malloc(sizeof(struct node));
temp->link=r;
r->link=NULL;
for(j=0;j<9;j++)
{
(r->name)[j]=*t;
t++;
}
}

return ;
}
void print(struct node *q)
{
struct node *temp;
temp=q;
while(temp->link!=NULL)
{
printf("\n");
puts(temp->name);
temp=temp->link;
}
puts(temp->name);
return ;
}





it also gives segmentation fault....
why???
contact at.......
pavankumar7860@gmail.com
Aug 11 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
void add (struct node **q,char *t)
{
struct node *temp,*r;
int i,j;
temp=(struct node *)malloc(sizeof(struct node));
temp=*q;
You are overwriting the address in temp that you just got from malloc() with the address inside the pointer of the function argument. Did you mean:
Expand|Select|Wrap|Line Numbers
  1. *q = temp;
  2.  
??
Aug 11 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.