Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

segmentation fault

Status
Not open for further replies.

sarahnade

Programmer
Dec 22, 2005
49
US
Alrighty, my first post. Here we go.

This is my code:

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
char *str;
struct node *next;
}node;

typedef struct List {
node *head;
}List;


List l1, l2;


void add(List strList, char *string){
if(strList.head != NULL){
strList.head->next = strList.head;
}
strList.head->str = string;
printf("\n%s\n", strList.head->str);
}
... etc etc


It compiles without a problem, but gives me a segmentation fault when I run it. Through endless "printf("\nklsdfjkl\n");" I've found the problem is in the "strList.head->str = string;". I know it has to to with memory and the *str array in the list nodes, but I don't know how to fix it. If I try to put "char *str = (char *)malloc(80 * sizeof(char));" in the struct, it gives a lot of wierd errors all over the place. Any help would be appreciated. Thanks!
 
My guess would be that you didn't initialize the List.head and/or node.str and/or node.next pointers to NULL somewhere and then tried to use them.
 
See also your add() prototype:
Code:
void add([b]List strList[/b], char *string);
/* instead of List* */
strList structure passed by value so you lost all argument link pointer modifications. In othen words, the function does nothing.
 
> if(strList.head != NULL)
Use a temp pointer to traverse from the head of the list to the tail (the tail being the node where ptr->next == NULL)

Then you need to
- allocate a new node
- allocate a string (don't forget to count the \0)
- append the new node to the end of the list
- copy the input string to the node.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top