The following code snippet allocates memory for a Node in the create() function, and creates a pointer called list to the pointer to the Node. It then allocates more memory for another Node in main(), and finally allocates memory for another node in test(). After allocating memory for a Node in test(), the data stored within list is changed. Why does this happen?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node Node;
typedef struct Node {
int data;
} Node;
Node **create(void)
{
Node *head = malloc(sizeof(Node));
head->data = 1;
Node **list = &head;
return list;
}
void test(void)
{
Node *node = malloc(sizeof(Node));
}
int main()
{
Node **list = create();
printf("Data after create(): %d\n", (*list)->data);
Node *node = malloc(sizeof(Node));
printf("Data after allocating memory for new node in main(): %d\n", (*list)->data);
test();
printf("Data after allocating memory for new node in test(): %d\n", (*list)->data);
return 0;
}
Sample output:
Data after create(): 1
Data after allocating memory for new node in main(): 1
Data after allocating memory for new node in test(): -129660600