0

I'm implementing a linked list program in C and the create_node function gives a warning: function returns address of local variable. I've read about using malloc, but I'd like to understand what the original problem and solution would be without it. Thanks.

struct list_node_s* Create_node(int val, struct list_node_s* node_p) {
   struct list_node_s temp;

   temp.data = val;
   temp.next_p = node_p;
   return &temp;
}  /* Create_node */
ckruczek
  • 2,361
  • 2
  • 20
  • 23
  • 1
    Related https://stackoverflow.com/q/4824342/694576 if not a duplicate to. – alk Sep 27 '17 at 06:08
  • It is something which very hard to explain on one leg but i will tried to be simpale The problem is when you create a variable without **malloc** - Behind the Scenes you put the variable on the stack - Segment of memory which save somethings about your current code segment . – Bizzu Sep 27 '17 at 06:32
  • when you jump to function you are add things to your stack from some point and when you finish (return from un-void function or finishes void function) you free all the things that you save from the enterance point. That mean - in your specific code you try to return address of something that you save on the stack but when you return you freed the stack - you try to return somthing that you "freed". . – Bizzu Sep 27 '17 at 06:32
  • Instead in malloc you have another code segment which called **Heap** the difference between the heap - at the Heap when you allocates variable (do malloc) you tell to OS - "Hey There, i'm the boss and don't touch that variable while i don't tell else" I tried to be simple but the best advice is to read about function call, Stack segment , Heap Segment.. – Bizzu Sep 27 '17 at 06:32

1 Answers1

0

The problem is that your temp variable is a local variable. It has function scope so it only exists as long as your program is in the function. This is usually implemented with a stack.

You should use malloc to get memory from the heap which is where all dynamic allocations are made from. This way the list and its nodes will exist until you explicitly destroy them with free.

The only other solution, which I don't recommend, is to build your list using recursive function calls. And as long as you use the list never return.

I saw that done one time. It was hideous. But possible.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131