-1

I have this function in C:

static Node* newNode(void* e){
Node n={e,NULL,NULL};
return &n;
}

And while compiling I get the following warning that I would like to understand why it happens:

warning: function returns address of local variable [enabled by default]

What kind of dangers are lurking behind this?

Thank you

Leonardo Marques
  • 3,721
  • 7
  • 36
  • 50
  • possible duplicate of [Pointer to local variable](http://stackoverflow.com/questions/4570366/pointer-to-local-variable) – Bo Persson Jul 01 '12 at 11:43

2 Answers2

5

Local variables are destroyed when you return from a function. Accessing them after the function returned is undefined behavior, don't do this.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

The warning is because the scope of the variable is local to the function - once the function is returned, that variable is no longer in scope, and it's value is undefined.