Reputation: 19
Suppose the code below,
int* foo(){
int a=5;
return &a;
}
int main(){
int* b=foo();
std::cout<<*b<<std::endl;
return 0;
}
My understanding of this program is that the life time of a is only in foo. After foo() is finished, a should not be valid. But since no function overwrites that chunk of stack, it still prints 5. Please correct me if this is wrong.
If the above is right, my question is, I called std::cout<<, the output stream; I actually called something, will it take some space on the stack? Or how exactly it works in memory. Thank you very much!!
Upvotes: 0
Views: 96
Reputation: 234815
"But since no function overwrites that chunk of stack". You don't know that for sure: there's nothing in the C++ standard that suggests that. I could build a standards-compliant compiler that overwrites that chunk of the stack. Perhaps my implementation of std::cout
would do that.
Formally the behaviour of your program is undefined. You can't say any more.
Upvotes: 2