[Issue 9651] New: Returning a newly-created slice by reference

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Mar 5 12:00:56 PST 2013


http://d.puremagic.com/issues/show_bug.cgi?id=9651

           Summary: Returning a newly-created slice by reference
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Keywords: accepts-invalid
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: gassa at mail.ru


--- Comment #0 from Ivan Kazmenko <gassa at mail.ru> 2013-03-05 12:00:51 PST ---
There is a handy warning in DMD of the sort "escaping reference to a local
variable".  Below is a similar case which is wrong code but does not generate a
similar warning.

We declare a function returning a reference to a slice.  Inside, we return a
reference to a newly-created slice of some array.  This is an error but goes
undetected by the compiler.

Example 1 (fixed length array):
-----
import std.stdio;

int [1] a;

ref int [] f ()
{
    return a [0..1];
}

void main ()
{
    auto s = f ();
    writeln (s);
}
-----

Example 2 (variable length array):
-----
import std.stdio;

int [] a;

ref int [] f ()
{
    return a [0..1];
}

void main ()
{
    a = new int [1];
    auto s = f ();
    writeln (s);
    auto t = f ();
    writeln (t);
}
-----

With DMD 2.062, the first example locally crashes with Access Violation after
printing ~10 Mb of some garbage array slice.  The second example prints an
empty slice (instead of [0]) for s and then crashes for t.

Now, while returning "ref int []" instead of "int []" might have its uses, in
my case it was a newbie mistake.  I just wanted to return a slice of lvalues
and didn't understand that the elements of the "int []" will be assignable for
free.  Thought I need an extra "ref" for that.

The case seems obvious: the function returns by reference an entity which was
created on the stack just a few instructions before that.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list