Bug 21291 – Array literal that escapes scope is allocated on stack

Status
RESOLVED
Resolution
DUPLICATE
Severity
regression
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2020-10-04T18:56:11Z
Last change time
2021-05-12T13:23:08Z
Keywords
accepts-invalid, safe
Assigned to
No Owner
Creator
Dennis
See also
https://issues.dlang.org/show_bug.cgi?id=20734

Comments

Comment #0 by dkorpel — 2020-10-04T18:56:11Z
I got memory corruption in @safe code because an array literal that was expected to be allocated by the Garbage Collector turned out to be put on the stack, as shown by the following @nogc code (must be compiled with -dip1000): ``` @safe: @nogc: struct S { int[] arr; static S create(int[] arr) pure @nogc { return S(arr); } } S createS() { // This should be GC allocated, but the compiler allows this // in this @nogc function and puts it on the stack! return S.create([0xABCD, 0xBCDE]); } void stompStack() { // set stack memory to reveal dangling stack pointers ubyte[128] stackMemory = 0x77; } extern(C) void main() { auto s = createS(); assert(s.arr[0] == 0xABCD); // likely still passes stompStack(); assert(s.arr[0] == 0xABCD); // likely does not pass } ``` It seems to be important that the array literal is in a pure static member function, though it might be possible to reduce the example further. This is introduced in DMD version 2.092 most likely because of https://github.com/dlang/dmd/pull/11039 though I don't think the wrong code is in that PR's code. I suspect that somewhere else in the compiler the 'return scope' flag is wrongfully inferred.
Comment #1 by ag0aep6g — 2020-10-04T19:14:32Z
(In reply to Dennis from comment #0) > It seems to be important that the array literal is in a pure static member > function, though it might be possible to reduce the example further. Duplicate of issue 20150? `-preview=dip1000` pretty much doesn't check `pure` functions at all, at the moment.
Comment #2 by dechcaudron+issues.dlang — 2021-04-23T19:41:14Z
This has also happened to me, no idea it could be due to -dip1000. So removing the compiler switch enables one to work around the issue (other than code not being suitable for @nogc)?
Comment #3 by dkorpel — 2021-05-12T13:23:08Z
*** This issue has been marked as a duplicate of issue 20150 ***