1

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
wojciech-graj
  • 25
  • 1
  • 5
  • 1
    `Node **list = &head;` You return the address of a local variable. After you return from the function, the lifetime of that variable ends and the memory can be reused. – Gerhardh Sep 25 '20 at 16:28
  • 1
    More on the topic: https://stackoverflow.com/questions/6897914/c-warning-function-returns-address-of-local-variable https://stackoverflow.com/questions/12380758/error-function-returns-address-of-local-variable – Gerhardh Sep 25 '20 at 16:32
  • How is this a list? There are no links between Nodes. – stark Sep 25 '20 at 16:46

1 Answers1

0

Your code is overly complicated and wrong, especially this :

Node **list = &head;
return list;

will return the address of a local variable which will no longer exist once the function is terminated.

You probably simply want this (although that code doesn't make much sense):

#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;
  return head;
}

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;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115