Need help in <varargs.h>

Wolfram Roesler wolfram at messua.informatik.rwth-aachen.de
Fri Jun 14 21:36:09 AEST 1991


tsai at Veritas.COM (Cary Tsai) writes:

>void ooprint(va_alist)
>va_dcl
>{
>	va_start(ap);
>	foo = va_arg(ap, char *);
>	if ((func = va_arg(ap, PFV)) != (PFV) 0) {
>		if ((client = va_arg(ap, char *)) != (char *) 0)
>			func(client);

... so you see you always call va_arg at least twice...

>	ooprint("ooprint"); /* WHY THIS STMT CAUSES CORE-DUMP? */

... but here you pass only one argument. So the 2nd call to va_arg returns
a random value. Since this is likely to be !=0, you call va_arg the 3rd
time, which gives you a random value again, and then call what you received
in the 2nd call as a function. But, a random value is very unlikely to be
a valid function adress... So why should it do anything except a core dump?

The problem is that a varargs function can never determine how many args were
passed to it. You may pass only one arg and use va_arg to retrieve more than
one, but you will get garbage and _not_ null pointers after the arg list
is exhausted.

BTW: to improve style, use /*VARARGS*/ in front of the function header, this
helps using lint on this function.

Greetings
\/\/olfram



More information about the Comp.lang.c mailing list