stack frame & dangling pointer weirdness
max haughton
maxhaton at gmail.com
Thu Apr 21 06:11:48 UTC 2022
On Thursday, 21 April 2022 at 05:49:12 UTC, Alain De Vos wrote:
> Following program:
> ```
> import std.stdio;
>
> void main() @trusted
> {
>
> int *p=null;
> void myfun(){
> int x=2;
> p=&x;
> writeln(p);
> writeln(x);
> }
> myfun();
> *p=16;
> writeln(p);
> writeln(*p);
> }
> ```
>
> outputs :
> 7FFFFFFFDFAC
> 2
> 7FFFFFFFDFAC
> 32767
>
> I don't understand why. Would it be possible to explain ?
When you pass a pointer to writeln conceptually it gets copied,
the address that is, but the memory the address points to is in
no man's land because it was in an old stack frame.
As such, this memory gets "overwritten" (at this point it's
invalid anyway) when you call writeln, so when you dereference it
you get something from the old stack of writeln rather than 16.
More information about the Digitalmars-d-learn
mailing list