简体   繁体   中英

Program crashes when printing LinkedList

I have a double linked list in C, which's nodes hold a char*. My struct for the node looks like this:

struct LinkedListNode{
char* data;
LinkedListNode* next;
LinkedListNode* prev; };

The struct for the LinkedList looks like this:

struct LinkedList{
LinkedListNode* head;
LinkedListNode* tail;};

head is a pointer to the first node of the list, tail is a pointer to the last node of the list. My problem is that I am trying to write a function for testing some standard functions for linked lists, which I am implementing for practice purposes. So I start by generating a list in the following function:

LinkedList* make_test_list(){
LinkedList* newlist = LinkedList_create();
printf("Hier2");
LinkedListNode n1;
LinkedListNode n2;
LinkedListNode n3;
LinkedListNode n4;
LinkedListNode n5;
n1.data = "abc";
n2.data = "def";
n3.data = "ghi";
n4.data = "pqr";
n5.data = "mno";
n1.next = &n2;
n2.next = &n3;
n2.prev = &n1;
n3.next = &n4;
n3.prev = &n2;
n4.next = &n5;
n4.prev = &n3;
n5.prev = &n4;
n5.next = NULL;
newlist->head = &n1;
newlist->tail = &n5;
return newlist;}

Which appears to be working fine, since I can reaccess the data of each node, if I try to print it inside of this function. LinkedList_create() contains the following code:

LinkedList* LinkedList_create(){
LinkedList* list = malloc(sizeof(struct LinkedList));
list->head = NULL;
list->tail = NULL;
return list;
}

So the next thing I want to do is printing my list in a seperate function. The function looks like this:

void LinkedList_print(LinkedList* list){    
LinkedListNode* p = list->head;
while(p != NULL)){
    printf("%s\n", p->data);
    p = p->next;
}}

But somehow it doesn't work. I think that I made a mistake while assigning my pointers. The call looks like this:

int main(){
LinkedList* myList = make_test_list();
printf("List before: \n");

LinkedList_print(myList);
}

I'd be glad if you could help me out on this one, since I'm quite new to C and new to managing memory allocation by myself.

Cheers!

Your LinkedListNode variables ( n1 - n5 ) are local to the make_test_list function. You need to allocate memory for them if you want to access them outside of that function.

For example:

LinkedListNode *n1 = malloc(sizeof(*n1));
n1->data = "abc";
...
newlist->head = n1;
...

Of course, you also want to make sure you free the memory later. I am also making the assumption that LinkedList_create is implemented correctly, since it isn't shown here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM