-1

What happens when a pointer to a local variable is returned by a function?

for example

int* foo()
{
    int local;
    int* ptr = &local;
    return ptr;
}

will compiler issue a warning or will it compile and produce unexpected results??

WARhead
  • 643
  • 5
  • 17

2 Answers2

4

What happens when a pointer to a local variable is returned by a function?

Undefined behaviour. Anything can happen. The compiler will give you a warning.

This is g++ warning for that mistake:

g++ -Wall -std=c++11 -O3 test.cpp -o test
warning: function returns address of local variable [-Wreturn-local-addr]
artm
  • 17,291
  • 6
  • 38
  • 54
2

Similar kind of question has already been asked : Stack Overflow, local pointer

There are somethings in C which are left for compiler vendor to implement in the way they like. The behaviour of such things are not defined by the creators. Compiler vendors can implement such things as in the way they feel easy and faster. This falls in the same category. The behaviour is undefined and depends on the compiler you are using.

One more such thing is use of more than one pre-increment (pre-decrement) and/or post-increment (post-decrement). When the same code runs on different compilers, you'll may get different output.

Community
  • 1
  • 1
AnkitAti
  • 186
  • 1
  • 4
  • 10
  • 1
    For more information on UB, better refer to http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior where you can find all the info you need – stefaanv Dec 06 '16 at 09:39