Reputation: 2668
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;
}
Upvotes: 0
Views: 167
Reputation: 3271
The fact that that memory address is popped from the top of the stack when it goes out of scope only means that it is freed, not overwritten. That is why you are getting the output "5".
Upvotes: 1
Reputation: 206528
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:
Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
Upvotes: 3