Mynicks Mynicks - 1 year ago 113
C Question

c language, is va_list bugged?

#include <stdio.h>
#include <stdarg.h>

int sumfinder(int num, ...);

int main(void)

int res,i,a,b,c;
scanf( "%d %d %d",&a, &b, &c );
res = sumfinder(a, b, c);// i also tried res=sumfinder(a,(int)b,(int)c); typecasting but to no avail
printf( "results= %d", res );
return 0;


int sumfinder( int maxsize, ... )
va_list argp;
int i;
int sum = 0;
va_start( argp, maxsize );
for( i = 0 ; i < maxsize; i++ )
sum += va_arg( argp, int );
return sum;

please enter input 2 3 4 , you get output=7, correct because 3+4=7 (2 stands for the number of input values)
now try...
2 3.0 4.0 and you get a wrong output, i tried to typecast but nothing corrects the problem.
the shocking thing is that the codeline sum += va_arg(argp, int ) should do the conversion from float to int for the input 2 3.0 4.0 but no no it does not , it expects to be fed with an int otherwise the problems begin...
ONE MORE sos tip is that the float data type does not work it return zero output, i am using windows10 and gcc ( ...and codeblocks IDE)

IS va_arg() bugged or what is going on?

Answer Source

You don't check the return value of the function scanf. This return value counts the number of successfully written arguments.

If you enter values 2 3.0 4.0 then the scanf function will return 2. The first and second argument will be read but the third argument will be left uninitialized. This happens because you try to read integers but pass floating points (3.0 is a floating point). Reading an int is indicated by the specifier %d:

scanf( "%d %d %d",&a, &b, &c );

The uninitialized variables are then used and passed to the function sumfinder causing undefined behavior.

The solution is to always check return value of functions and make sure the execution proceeds on a valid path.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download