Isn’t this supposed to produce a segfault?
When I run the code the output is 5. Example: http://ideone.com/gV2Nv
#include <iostream>
using std::cout;
using std::endl;
int* foo(int a) {
int b = a;
int* c = &b;
return c;
}
int main() {
int* a = foo(5);
cout << *a << endl;
return 0;
}
Returning an pointer to an local variable in the function is an Undefined Behavior.
Undefined Behavior does not warranty a segmentation fault. It merely means that any behavior is possible and the program can behave in any way.
It is a common misconception that Undefined Behavior means the code should produce a segmentation fault, the truth is that standard does not require any specific behavior in cases where the code invokes an Undefined Behavior and hence the name.
C++ Standard section 1.3.24 states: