Thread overview
[Issue 19111] Returning a reference to local array results in garbage
Jul 23, 2018
Mike Franklin
Jul 26, 2018
anonymous4
Jul 26, 2018
anonymous4
July 23, 2018
https://issues.dlang.org/show_bug.cgi?id=19111

Mike Franklin <slavo5150@yahoo.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |safe
                 CC|                            |slavo5150@yahoo.com

--- Comment #1 from Mike Franklin <slavo5150@yahoo.com> ---
Using `@safe` with `-dip1000` seems to catch the error:

import std.stdio;

@safe:

int[] makeRef(int[] a)
{
    return a;
}

int[] getArray()
{
    int[10] a;
    a []= 42;
    return makeRef(a);
}

void main()
{
    writefln("%s",getArray());
}

$ dmd -dip1000 test.d

https://run.dlang.io/is/hIoDsB

onlineapp.d(14): Error: reference to local variable a assigned to non-scope parameter a calling `onlineapp.makeRef`

--
July 26, 2018
https://issues.dlang.org/show_bug.cgi?id=19111

anonymous4 <dfj1esp02@sneakemail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
         Resolution|---                         |INVALID
                 OS|Linux                       |All

--- Comment #2 from anonymous4 <dfj1esp02@sneakemail.com> ---
Safe D and DIP1000 were created for this.

int[] makeRef(return int[] a)
{
    return a;
}

int[] getArray()
{
    int[10] a;
    a []= 42;
    return makeRef(a);
}

void main()
{
    writefln("%s",getArray());
}

Error: returning makeRef(cast(int[])a) escapes a reference to local variable a

--
July 26, 2018
https://issues.dlang.org/show_bug.cgi?id=19111

--- Comment #3 from anonymous4 <dfj1esp02@sneakemail.com> ---
(In reply to Alex from comment #0)
> I suggest that int[10] should be on the heap unless the compiler can be sure that there isn't a way for a reference to escape.
LDC does the opposite: it performs D-specific optimizations and promotes heap allocations to stack if it detects that the allocation is properly scoped.

--