Reputation:
I have the following program, with the following output written in C.
I expect after prepending a value for my tail to be 40 and my head 30, but it is not.
Am I making a mistake with memory allocation of the structs or is it something less obvious than that?
I am using the GCC compiler on Mac OSX.
#include <stdio.h>
struct LinkedListNode {
int data;
struct LinkedListNode *next;
};
struct LinkedList {
int size;
struct LinkedListNode *head;
struct LinkedListNode *tail;
};
struct LinkedList create_linked_list(){
struct LinkedList linkedList;
linkedList.size = 0;
linkedList.head = NULL;
linkedList.tail = NULL;
return linkedList;
}
struct LinkedList prepend(struct LinkedList *linkedList, int data){
struct LinkedListNode linkedListNode;
linkedListNode.data = data;
linkedListNode.next = linkedList->head;
linkedList->head = &linkedListNode;
if(linkedList->tail == NULL){
printf("Setting tail to: %d\n", data);
linkedList->tail = &linkedListNode;
}else{
printf("The tail is: %d\n", linkedList->tail->data);
}
linkedList->size = linkedList->size + 1;
return *linkedList;
}
int main(){
struct LinkedList linkedList;
linkedList = create_linked_list();
linkedList = prepend(&linkedList, 40);
struct LinkedListNode head = *linkedList.head;
struct LinkedListNode tail = *linkedList.tail;
printf("%d\n", head.data);
printf("%d\n", tail.data);
printf("%d\n", linkedList.size);
linkedList = prepend(&linkedList, 30);
head = *linkedList.head;
tail = *linkedList.tail;
printf("%d\n", head.data);
printf("%d\n", tail.data);
printf("%d\n", linkedList.size);
}
Output:
Setting tail to: 40
40
40
1
The tail is: 30
30
30
2
Upvotes: 1
Views: 99
Reputation: 409136
One major problem is here:
linkedList->head = &linkedListNode;
Here you make linkedList->head
point to the location of the local variable linkedListNode
. That variable will go out of scope once the function returns, and the pointer will become a stray pointer that you no longer can dereference without having undefined behavior.
The solution to this problem is to allocate the LinkedListNode
structure dynamically using malloc
.
Upvotes: 4