[Issue 21745] Closure created in struct constructor passed to class constructor refers to expired stack frame

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Mar 25 20:51:48 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=21745

--- Comment #12 from Walter Bright <bugzilla at digitalmars.com> ---
> super weird

It can indeed be, because what's happening is hidden behind implicit variables,
complex types, templates, etc. This is why I recommend rewriting confusing
examples in terms of simple pointers and types. In this case,

    int i;
    int* p = &i;
    int func = { return *p; }
    return &func;

i is a local variable.
p is a local variable that references i.
func references p.
&func escapes the stack frame.
Therefore, p is allocated in a heap allocated closure, rather than on the
stack.

BUT

p refers to another local i, which IS allocated on the stack.

Hence a reference to the local stack frame escapes, and hello stack corruption.
Unfortunately, this kind of corruption can often appear to work and pass all
the tests. But it will at some point start failing, and can be hard to find.

To fix the problem, i must be allocated in longer lived storage than the
lifetime of &func.

--


More information about the Digitalmars-d-bugs mailing list