Mynicks
Mynicks

Reputation: 223

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 );
    va_end(argp);
    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?

Upvotes: 0

Views: 238

Answers (2)

Gerhardh
Gerhardh

Reputation: 12404

You make a wrong assumption:

the codeline sum += va_arg(argp, int ) should do the conversion from float to int for the input 2 3.0 4.0.

In your function you do not have any float values. In main your parameters are of type int, whatever you type for scanf. They do not become floats just because you enter a .0 . And changing format in scanf would not make a difference unless you change type in the definition.

Upvotes: 1

2501
2501

Reputation: 25763

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.

Upvotes: 4

Related Questions