FAQ 30.16 Why do programs with variable-length argument lists crash?

Because variable-length argument lists use bitwise copy, which is dangerous in many cases. There are times where variable-length argument lists don't cause a problem (printf comes to mind). But it is wise to avoid using them unless there is some compelling reason.

Objects passed into ellipses (...) are passed via bitwise copy. The parameter objects are bitwise copied onto the stack, but the va_arg macro uses the copy constructor to copy the pile of bits from the stack. The technical term for this asymmetry is ouch.

 #include <cstdarg> class Fred { public:   Fred() throw();   Fred(const Fred& x) throw();   Fred& operator= (const Fred& x) throw();  ~Fred() throw(); }; void doSomethingWith(Fred x) throw(); void f(int count, Fred first...) throw() {   va_list ap;   va_start(ap, first);   doSomethingWith( first );   for (int i = 1; i < count; ++i) {     Fred x = va_arg(ap, Fred);     doSomethingWith( x );   } } int main() {   Fred a, b, c;   f(3, a, b, c); } 

"Ladies and gentlemen, this is your pilot speaking; please fasten your seat belts in preparation for the air turbulence ahead."

main()'s three Fred objects are constructed via Fred::Fred(). The call to f(int,Fred...) passes these Freds using bitwise copy. The bitwise copies may not be properly initialized Fred objects and are not logical copies of a, b, and c. Inside f(int,Fred...), the va_arg macro uses a pointer cast (shudder) to create a Fred*, but this Fred* doesn't point to a valid Fred object because it points to a bitwise copy of a Fred object. The va_arg macro then dereferences this (invalid) pointer and copies the pile of incoherent bits (via Fred's copy constructor) into the local variable, x.

If Fred has nontrivial copy semantics, the chances that the bitwise copy is the same as a logical copy is remote at best.

Variable-length argument lists are evil.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net