teafellow teafellow - 3 years ago 151
C Question

Pointer Behaviour in C: Initializing Linked List Head after Node

I am a little puzzled by this C behaviour. If I initialize the "head" pointer after the node it seems that it does not continue holding on to the next elements. Sample code below:

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


typedef struct node {
int value;
struct node* next;
} node;

int main(void)
{
node* head = NULL;
node* current = malloc(sizeof(node));
current->value = 1;

if(head == NULL)
head = current;

current = current->next;

current = malloc(sizeof(node));
current->value = 2;

printf("%d\n", current->value); // 2
printf("%d\n", head->value); // 1
printf("%d\n", head->next->value); //Segmentation fault: 11, Should be 2

return 0;

}


As far as I understand: I malloc() memory for current, then set the value. Then set head equal to current. They now both point to the same node.

Then I make current = current->next, malloc memory and set the value.

Why does head->next->value not point to the same place as current->value?

Answer Source

This does not do what you think it does:

current = current->next;

Prior to this statement, you have this:

             ---------------
current ---> |   1  |   ?  |
             ---------------

current points to an area of memory big enough for a node where the value of value is 1 and the value of next is unknown since malloc returns uninitialized memory.

After this statement, current contains the garbage value that current->next contained. When you then do this:

current = malloc(sizeof(node));

You change the value of current to whatever malloc returned, overwriting the prior value.

To do what you intended, you would need to do this:

current->next = malloc(sizeof(node));
current = current->next;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download