Return a dynamic array: real bug!
Gilles G.
schaouette at free.fr
Wed Jul 4 03:12:47 PDT 2007
Replying to myself...
I just realised that dmd issues an error on the previous code (Error: escaping reference to local a) while gdc based on dmd 1.007 does not!
However, I really ran into trouble yesterday returning a static array using dmd. Here is how I do it:
import std.stdio;
int[] testGood()
{
int a[]; a.length=2;
a[]=1;
return a;
}
int[] testBad()
in { /*nothing*/ }
out{ /*nothing too*/}
body
{
int a[2];
a[]=1;
return a;
}
int main()
{
int b[];
b = testGood();
writef("Good test:\n");
writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
b = testBad();
writef("Bad test:\n");
writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
return 0;
}
Then the DMD will just compile fine and the ouput is
>Good test:
> b[0]=1, b[1]=1
> b[0]=1, b[1]=1
>Bad test:
> b[0]=4280528, b[1]=4298584
> b[0]=4280472, b[1]=4280528
So it seems that using the in out and body statement changes the behavior of DMD...
Maybe I should file a bug report now.
--
Gilles
Gilles G. Wrote:
> Hello,
> I went into trouble returning a dynamic array from a function. For example:
> import std.stdio;
> int[] testGood()
> {
> int a[]; a.length=2;
> a[]=1;
> return a;
> }
>
> int[] testBad()
> {
> int a[2];
> a[]=1;
> return a;
> }
>
> int main()
> {
> int b[];
> b = testGood();
> writef("Good test:\n");
> writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
> writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
> b = testBad();
> writef("Bad test:\n");
> writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
> writef(" b[0]=%d, b[1]=%d\n",b[0],b[1]);
> return 0;
> }
> This code outputs:
> >Good test:
> > b[0]=1, b[1]=1
> > b[0]=1, b[1]=1
> >Bad test:
> > b[0]=0, b[1]=1
> > b[0]=0, b[1]=1
>
> I guess this is the good behavior since I should not return a static array from a function, but the compiler _should_ issue a warning here... or not?
>
> --
> Gilles
>
More information about the Digitalmars-d-learn
mailing list