When does a pointer become dangling in C/C++? | Why isn't this example dangling?

Calin Baenen - Oct 27 '21 - - Dev Community

All testing has been done on SoloLearn's C++ playground.

So, I was planning on making a post on a custom pointer datatype, and I was playing around with (raw-)pointers, and I wanted to test something, to see if I could (purposefully) get a pointer to dangle, so I tried something I was certain would work:

int main() {
    int* p;
    {
        int i = 10;
        p = &i;
    }
    std::cout << p;
}
Enter fullscreen mode Exit fullscreen mode

and I was baffled when I saw 10 in the output box.
So, I tried (virtually) the same thing in C:

int main() {
    int* p;
    {
        int i = 10;
        p = &i;
    }
    printf("%d", *p);
}
Enter fullscreen mode Exit fullscreen mode

and I got 10 again.

I thought the conditions for a pointer to become dangling was for the referenced value to leave the current scope. But as it's apparent, even though i (and its value) leaves the scope. (Yes, it is leaving the scope, for anyone who wants to object. This is called a guard-scope, and allows temporary variables to exist.)
So, what are the actual conditions for a pointer to become dangling? And/or why is my example NOT dangling?

Thanks!
Cheers!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .