convert static arrays to dynamic arrays and return, have wrong data.

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Sun Nov 9 07:07:06 PST 2014


On Sun, Nov 09, 2014 at 08:29:58AM +0000, AlanThinker via Digitalmars-d wrote:
> It seems that, D's array is strange,
> It can implicit convert static arrays to dynamic arrays no error and
> no warning.
> But when I return the converted arrays out the function.
> Outside function will get some wrong data.
> 
> It may very easily cause some bug because no error when convert static
> arrays to dynamic arrays.
[...]

Yes, this is a known problem. There may even be an issue filed in
bugzilla about it (if not, please file one!). The problem is that local
static arrays are allocated on the stack, and the implicit conversion to
dynamic array is simply taking a slice of the stack-allocated array. As
a result, after the function returns, the slice is now pointing at stack
memory that has gone out of scope.

I'm not sure if the current compiler issues a warning / error if you do
this in @safe code, but IMO it should do this even in @system code since
the implicit conversion is almost never correct.


T

-- 
People who are more than casually interested in computers should have at
least some idea of what the underlying hardware is like. Otherwise the
programs they write will be pretty weird. -- D. Knuth


More information about the Digitalmars-d mailing list