www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Unsafe variadic arguments -> array assignment

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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.
Oct 04 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
H. S. Teoh:

 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.
The D compiler must do its best to help avoid similar bugs. See also: http://d.puremagic.com/issues/show_bug.cgi?id=5212 Bye, bearophile
Oct 05 2012