Results 1 to 7 of 7
Hi,
I hav one structure like this
struct linked_list {
struct linked_list *next;
char *data;
};
struct linked_list *tmp = NULL;
char *test_string = "some data";
tmp = malloc(sizeof(*tmp));
strncpy(tmp->data,test_string,strlen(test_string));
...
- 06-07-2007 #1Linux Newbie
- Join Date
- Oct 2006
- Posts
- 107
linked list doubt
Hi,
I hav one structure like this
struct linked_list {
struct linked_list *next;
char *data;
};
struct linked_list *tmp = NULL;
char *test_string = "some data";
tmp = malloc(sizeof(*tmp));
strncpy(tmp->data,test_string,strlen(test_string));
iam getting error segmentation fault. can any body help me .
Thanks in Advance
- 06-07-2007 #2Linux Enthusiast
- Join Date
- Aug 2006
- Posts
- 631
must be:Code:tmp = malloc(sizeof(*tmp));
You must also allocate memory for the member data of the struct.Code:tmp = malloc(sizeof(struct linked_list));
Regards
- 06-12-2007 #3Just Joined!
- Join Date
- Jun 2007
- Posts
- 14
linked list doubt
Hi,
You have to allocate memory of size struct linked list not of size *tmp because of sizeof(*tmp) allocates memory for the pointer not for the structure. That's why you are getting segmentation fault.
Try the following
tmp = malloc(sizeof(struct linked_list));
- 06-12-2007 #4Linux Enthusiast
- Join Date
- Aug 2006
- Posts
- 631
- 06-14-2007 #5
- 06-14-2007 #6
In C, casts from (void *) are made automatically. In C++, you would need to specifically make the cast.
I suppose if it helps you to manually cast, it wouldn't hurt. But it's pretty rare to see it: we all know that malloc is allocating the memory for that structure.DISTRO=Arch
Registered Linux User #388732
- 06-18-2007 #7Linux User
- Join Date
- Oct 2004
- Location
- /dev/random
- Posts
- 404
The main reason for the segfault is
without allocating memory for tmp->data.Code:strncpy(tmp->data,test_string,strlen(test_string));
The statementis perfectly legal and valid.Code:tmp = malloc(sizeof(*tmp));
The Unforgiven
Registered Linux User #358564


Reply With Quote
