the following is my code:
#include <iostream>
int* foo() {
int a = 5;
return &a;
}
int main() {
int* p = foo();
std::cout << *p; // Output: 5
*p = 8;
std::cout << *p; // Output: 8
}
I expected this to crash or give garbage, but I'm accessing memory that should no longer be valid (a
is local to foo()
) but the output was:
58
no error and crash why?
Undefined behavior means that the behavior of a pattern is not defined by the standard so it is unreasonable to have any expectations in such cases. Maybe it will seem to work. Or it will throw an error. Your mistake in this situation was to have an expectation, namely:
I expected this to crash or give garbage, but I'm accessing memory that should no longer be valid
don't expect a crash, nor to get garbage, nor to not access memory that is no longer valid.