Consider:
#include <iostream>
int* dont() {
int num = 10;
int* num_ptr = #
return num_ptr;
}
int main() {
int* a = nullptr;
a = dont();
std::cout << *a;
}
This is my code sample. I think 'a' would have a garbage value, but the memory is still alive. What is it? (I use Visual Studio 2022 for my IDE.)
Precisely what I want to know is pointer 'a' must be a dangling pointer. But it wasn’t. I cannot understand this situation...
Returning a pointer to a local variable and then dereferencing that pointer invoke undefined behavior. Anything can happen, but that doesn't mean you necessarily get a garbage value. The program can "work" as an option.
The likelihood of this option is increased in this case as no other functions are called in the interim, reducing the odds that the memory location you're accessing has been overwritten.