stack frame & dangling pointer weirdness

bauss jj_1337 at live.dk
Thu Apr 21 06:21:14 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  ?

See my comment for some ELI5 of what's going on.

Of course it's a bit more complicated than that, but I hope it 
gets the point across.

```
void main() @trusted
{

int *p=null; // P is null obviously
void myfun(){
	int x=2;
	p=&x; // Sets the address of p to the address of x, which is on 
the stack of myfun
	writeln(p); // Writes the address of p
	writeln(x); // Writes the value of x (same as value of p)
}
myfun(); // We call myfun
// Any memory that was in the stack of myfun is invalid here, 
returning to the stack of main.
*p=16; // Sets the value of p to 16, but p points to the address 
of an invalid memory location, since x was on the stack within 
myfun and thus isn't valid outside of myfun
writeln(p); // Writes the address of p, which is the same since 
the address of p was stored on the stack of main
writeln(*p); // Attempts to write the value of p, which points to 
an "invalid" memory address, or at least it's now something 
completely different than it was before, considering the stack of 
myfun is gone, so it writes out a garbage value
}
```


More information about the Digitalmars-d-learn mailing list