Bug 5541 – Disallow escaping of references to stack-allocated memory

Status
RESOLVED
Resolution
WORKSFORME
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-02-07T13:05:00Z
Last change time
2013-01-16T17:36:55Z
Keywords
accepts-invalid
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2011-02-07T13:05:29Z
This is D2 code: struct Foo { int x; } Foo* bar() { Foo f = Foo(1); return &f; } void main() {} DMD 2.051 raises a compile-time error: test.d(6): Error: escaping reference to local f But this code compiles and runs with no errors with DMD 2.051. I think DMD has to statically disallow code like this too: struct Foo { int x; } Foo* bar() { return &(Foo(1)); } void main() {}
Comment #1 by yebblies — 2012-01-31T20:25:08Z
(In reply to comment #0) > But this code compiles and runs with no errors with DMD 2.051. I think DMD has > to statically disallow code like this too: > > > struct Foo { > int x; > } > Foo* bar() { > return &(Foo(1)); > } > void main() {} Believe it or not, this is valid code. In D struct literals are currently lvalues, and not allocated on the stack at all. See issue 5889.
Comment #2 by timon.gehr — 2012-02-09T15:21:53Z
This is not about struct literals being lvalues, Walter states this is by design anyway. Furthermore, struct literals are certainly allocated on the stack and what bearophile shows is not valid code. struct Foo { int x; } Foo* bar() { return &(Foo(1)); } void qux(ref Foo f,int x){ writeln(f.x); } void main() { Foo* x = bar(); qux(*bar(),2); } compiling and running for 32 bit prints garbage, and looking at the disassembly shows that the literal is indeed allocated on the stack.
Comment #3 by yebblies — 2013-01-16T17:36:55Z
None of this compiles any more with 2.062 head