Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 27, 2021 10:01 pm GMT

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

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;}

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);}

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!


Original Link: https://dev.to/baenencalin/when-does-a-pointer-become-dangling-in-cc-why-isnt-this-example-dangling-4p1p

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To