[Issue 23322] New: std.functional.toDelegate on functor can produce dangling reference

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Sep 3 17:43:16 UTC 2022


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

          Issue ID: 23322
           Summary: std.functional.toDelegate on functor can produce
                    dangling reference
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: safe
          Severity: normal
          Priority: P1
         Component: phobos
          Assignee: nobody at puremagic.com
          Reporter: schveiguy at gmail.com

A little known feature of `toDelegate` is that it can take a functor (a struct
with opCall) and return a delegate to that.

However, I noticed that it takes its parameter as `auto ref`, meaning if it's a
struct functor, the delegate it will return is a dangling pointer at the
stack-stored struct.

example to cause the problem:

```d
import std.functional;
import std.stdio;

struct S
{
    int x;
    this(int x) { this.x = x; }
    int opCall() { return x;}
}

void main()
{
    auto dg = toDelegate(S(5));
    writeln("garbage garbage"); // to smash the stack
    writeln(dg());
}
```

On run.dlang.io, it produced the result:

garbage garbage
4517416

Clearly not the 5 that was expected.

`toDelegate` can't be marked @safe partly because of this, but also it probably
should never return a delegate to a local stack variable that is about to go
away, even in @system code.

--


More information about the Digitalmars-d-bugs mailing list