2

I´m just playing around with C when I got a problem I can´t figure out.

I have a struct, lets say

typedef struct Node
{
    void * data;
    int id;
}Node;

And my program looks like

void Node_Init(Node *node)
{
   node = malloc(sizeof(Node));
   node->id = 5;
}

int main()
{
   Node *node;
   Node_Init(node);
   printf("ID %d", node->id);
}

When I run this code and node->id gets printed I get a random number? It´s like node->id gets allocated on the stack and not the heap?

Because when I do Node *node; If I do Node *node = malloc(sizeof(Node)); It works, but If I remember correctly its not needed to do like that. Anyone can help me out saying why this happens?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Labba
  • 121
  • 1
  • 10

1 Answers1

3
void Node_Init(Node *node) 
{    
      node = malloc(sizeof(Node));   
      node->id = 5; 
}

int main() 
{    
     Node *originalnode;    
     Node_Init(originalnode);    
     printf("ID %d", node->id); 
}

Why your solution does not work? When you call the function the parameter node becomes local in the Node_Init scope. Then you assign the node (which is local) the value returned by malloc. After the function return value of this node becomes unavailable. No change in the originalnode' It is same uninitialised as it was before. your function is an equivalent of:

void Node_Init(Node *node) 
{
      Node *x;    
      x = malloc(sizeof(Node));   
      x ->id = 5; 
}

To change the originalnode you need to:

  1. Pass the pointer to the originalnode. When you dereference this pointer to originalnode, and assign the value to the dereferenced object you change the originalnode 2. Return the node and assign it to the originalnode

    void Node_Init(Node **node)
    {
       *node = malloc(sizeof(Node));
       (*node)->id = 5;
    }
    
    int main()
    {
       Node *node;
       Node_Init(&node);
       printf("ID %d", node->id);
    }
    

or

void *Node_Init(void)  // or Node *Node_Init(void)
{
   Node *node
   node = malloc(sizeof(Node));
   node->id = 5;
   return node;
}

int main()
{
   Node *node;
   node = Node_Init();
   printf("ID %d", node->id);
}

Dont forget to free it after the use

0___________
  • 60,014
  • 4
  • 34
  • 74