Weird struct stuff
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 1 18:01:43 PST 2016
On 03/01/2016 05:11 PM, asdf wrote:
> import std.stdio : writeln;
>
> struct foo
> {
> long* bar;
>
> this (long l)
> {
> long d = l;
> bar = &d;
Unfortunately, 'bar' is pointing at the temporary stack-based variable 'd'.
> }
> }
>
> int main()
> {
> foo f = foo(12345);
> writeln(*f.bar);
That's undefined behavior because f.bar is pointing at a dead object (d).
> //writefoo(f);
> writeln(*f.bar);
>
> return 0;
> }
>
> void writefoo(foo f)
> {
> writeln(*f.bar);
> }
>
>
> If I compile this with dmd, I get the obvious output
> 12345
> 12345
Yeah, undefined behavior sometimes produces "obvious" outputs. ;)
Ali
More information about the Digitalmars-d-learn
mailing list