return table from local resource

monarch_dodra monarch_dodra at gmail.com
Mon Jun 25 03:51:41 PDT 2012


Just started using D. I've got a very strong background in C++. I
was making this toy program:

[CODE]import std.stdio;

int[] fun()
{
     int[3] statictab;
     writeln(statictab);
     int[] dyntab = statictab;
     writeln(dyntab);
     return dyntab;
}

void main()
{
     int[] a = fun();
     writeln(a);
}[/CODE]

First, I create a method called "fun". In it, I create on the
stack a table. I create a dynamic array that references that
table. I return the dynamic array.

Of course, this is the classic "return reference to local"
problem. I can tell the problem is there because the output I get
is:

[CODE]
[0, 0, 0]
[0, 0, 0]
[1637924, 4217180, 10] //Garbage
[/CODE]

What bothers me is that it was my understanding that the D
language standard protected me from this kind of undefined
behavior. I did make use of anything unsafe, so what gives?
Compiler not catch it but should have?

Or am I just mistaken about the safe guarantees of D?

What bothers me even more is this:

[CODE]@safe

int[] fun()
{
     int[3] statictab;
     int[] dyntab = statictab;
     return dyntab;
}

void main()
{
     int[] a = fun();
}
[/CODE]

This time, in "Safe" mode...


More information about the Digitalmars-d mailing list