#include <iostream>
int main()
{
int* aPtr = nullptr;
{
int a = 3;
aPtr = &a;
}
std::cout << *aPtr << std::endl;
return 0;
}
Output
3
I am able to access a
through aPtr
.
a
is not deallocated even after it goes out of
scope. a
is deallocated only after the function in
which it is defined unwinds. #include <iostream>
struct Box
{
Box(int a_)
:a(a_)
{}
int getValue() const { return a;}
~Box()
{
std::cout << "Destructor called" << std::endl;
}
private:
int a;
};
int main()
{
Box* boxPtr = nullptr;
{
Box box = 23;
boxPtr = &box;
}
std::cout << boxPtr->getValue() << std::endl;
return 0;
}
Output
Destructor called
23
I am able to access box
through boxPtr
even after destructor of box
is called.
As mentioned in the comments, in both cases you are facing undefined behavior (so anything is allowed to happen). The stack variables are destroyed as soon as they go out of scope, the memory occupied by them is freed, although usually it's not immediately overwritten (at least in simple cases like above), therefore the pointer pointing at such variable, might sometimes exhibit more or less "valid" properties (as in it looks like the object is still valid), despite it clearly dangling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With