Reputation: 4073
I'm fairly new to C and I know I'm probably doing something wrong with pointers but I just can't seem pinpoint what I'm doing wrong.
Here's the structs and functions for the linked list:
// node structure
struct Node {
int val;
struct Node* next;
};
// singly linked list structure
struct LinkedList {
int size;
struct Node* head;
} LinkedList = {0, NULL};
// insert at head function
void InsertHead(struct LinkedList* list, int val) {
struct Node* node = malloc(sizeof(struct Node));
node->val = val;
node->next = list->head;
list->head = node;
list->size++;
}
// print values in list
void PrintList(struct LinkedList* list) {
struct Node* node = list->head;
while (node != NULL) {
printf("%d, ", node->val);
node = node->next;
}
printf("\n");
}
When I try to call PrintList with the following code:
// main function
int main() {
struct LinkedList* mylist = malloc(sizeof(LinkedList));
InsertHead(mylist, 4);
InsertHead(mylist, 3);
InsertHead(mylist, 1);
// printf("%d, ", mylist->head->val);
// printf("%d, ", mylist->head->next->val);
// printf("%d, ", mylist->head->next->next->val);
// printf("\n");
PrintList(mylist);
return 0;
}
I get the error Segmentation fault: 11
When I run remove the call to PrintList function and uncomment the printf statements, I get the desired output:
1,3,4,
What am I missing here?
Upvotes: 0
Views: 113
Reputation: 23342
You never intialize the struct LinkedList
you allocate at the top of main()
.
So when you're walking the list to print it, after the three elements you inserted explicitly, the next
field of the last one will contain whichever garbage was in the head
field of the original LinkedList
when it was allocated.
To fix this, you can either allocate it with calloc
instead (which explicitly zeros out the allocated memory befor it's given to you), or write a helper function that both allocates and explicitly initializes a struct LinkedList
.
Upvotes: 1