-
segmentation fault
Im getting a segmentation error....can anyone help :o please
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char *data;
struct node *next;
};
int main()
{
struct node *head, *curr;
int i=0;
char *str=malloc(5);
/* head=NULL; */
head=(struct node*) malloc (sizeof(struct node));
curr=head;
printf("\nPlease enter data : ");
for (i=0; i<5; i++)
{
str[i]=getchar();
if (str[i]=='\n')
i=5;
}
strcpy(str, curr->data);
printf("\n Data is : %s", curr->data);
return 0;
}
-
The order of the arguments to the strcpy function appear to be reversed and you haven't allocated any space for the data pointer within the node pointed to by curr.
-
Also the string should be terminated with '\0' to make your printf look nice
str[i] = '\0'
aswell as
curr->data = (char *) malloc(5 * sizeof(char));
to allocate memory for a 5 char string