0
#include <iostream>

int* retPointer()
{
    int x=10; //same as auto int x =10;
    return &x;
}

int main(int argc, char **argv)
{
    std::cout<<"x="<<*retPointer()<<std::endl;
    return 0;
}

In the example above I am returning a pointer that points to a local variable to stack. When I print the value pointed by this pointer in the man() then I should get a seg-fault. The variable x should go out of scope when I return from function retPointer(). So when try to access the value in main() should I not get a segmentation fault? Am I missing something here?

Output is = x=10

chollida
  • 7,834
  • 11
  • 55
  • 85
Soumyajit Roy
  • 463
  • 2
  • 8
  • 17

2 Answers2

5

The x object does go out of scope when returning from retPointer(), and dereferencing a pointer to an object whose lifetime has expired is Undefined Behavior.

A program having Undefined Behavior means that anything could happen, including a crash, behaving as if nothing happened (like *retPointer() returning a normal value such as 10), or formatting your hard drive.

Although the last option is quite unlikely, you definitely do not want to have Undefined Behavior in your program. Do not ever return pointers or references to local objects with automatic storage.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
0

When I print the value pointed by this pointer in the man() then I should get a seg-fault.

You should? Where in the spec does it say this will happen?

You're invoking undefined behaviour. Anything could happen.

James M
  • 18,506
  • 3
  • 48
  • 56