Unsafe variadic arguments -> array assignment
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Oct 4 22:17:48 PDT 2012
This code (rightfully) generates an error:
int[] f(int[] args...) {
return args;
}
However, this code doesn't generate any warning or error:
import std.conv;
import std.stdio;
class C {
real[] val;
this(real[] v...) {
val = v;
}
override string toString() {
return to!string(val);
}
}
C f() {
return new C(1.0);
}
void main() {
auto e = f();
writeln(e);
}
This code may _appear_ to work on some machines, but actually there is a
nasty bug lurking in it: the ctor's arguments are on the call stack, and
'val' is left referencing an array on the stack which has gone out of
scope. When dereferenced later, it will quite likely read garbage
values, because that part of the stack has been overwritten with other
stuff in the interim! On my machine, the output is:
[1.93185]
(It should be [1.0].)
Rewriting the ctor to read as follows fixes the problem:
this(real[] v...) {
val = v.dup;
}
The compiler should not allow this unsafe copying of a variadic argument
list to an object member. Is this a known issue? I'll file a new bug if
not.
T
--
ASCII stupid question, getty stupid ANSI.
More information about the Digitalmars-d
mailing list