Bug 23322 – std.functional.toDelegate on functor can produce dangling reference

Status
NEW
Severity
normal
Priority
P3
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2022-09-03T17:43:16Z
Last change time
2024-12-01T16:40:19Z
Keywords
safe
Assigned to
No Owner
Creator
Steven Schveighoffer
See also
https://issues.dlang.org/show_bug.cgi?id=18171
Moved to GitHub: phobos#9843 →

Comments

Comment #0 by schveiguy — 2022-09-03T17:43:16Z
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.
Comment #1 by robert.schadek — 2024-12-01T16:40:19Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/phobos/issues/9843 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB