www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 23322] New: std.functional.toDelegate on functor can produce


          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 puremagic.com
          Reporter: schveiguy 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:

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

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

garbage garbage

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.

Sep 03 2022