简体   繁体   中英

Why does this GNU C variadic function return a huge number?

I'm looking at this example of a variadic function in C, written GNU.org. My OS is Debian 8.6.

Here's my slight variation on it, filename is ex.c :

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

int addEmUp(int count,...){
    va_list ap; // where list of arguments are stored
    int i, sum;

    va_start(ap,count); // initialize the argument list

    sum=    0;
    for(i=0; i<count; i++)
        sum += va_arg(ap,int);  // get the next argument value

    va_end(ap); // clean up

    return sum;
}

int main(void){
    printf("%d\n", addEmUp(3,4,5,6));
    printf("%d\n", addEmUp(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    printf("%d\n", addEmUp(10,10,10,10));
    return 0;
}

Here's my makefile _example.mak :

CFLAGS=-Wall -g
CFILE=ex

run:
    cc $(CFILE).c -o $(CFILE) $(CFLAGS)
    ./$(CFILE)
    rm -f $(CFILE)

The output when I open the terminal and run make -f _example.mak :

./ex
15
55
1141373223
rm -f ex

Why does the third addEmUp() print 1141373223 ?

You have undefined behavior.

You sent 10 as first argument, but you call addEmUp() with only 3 additional arguments.

printf("%d\n", addEmUp(3, 10, 10, 10));

When you have an undefined behavior, you can't know what will happen. When your function addEmUp() get too far with va_arg() . You can cause a lot of thought:

  • segmentation fault
  • wrong behavior (what you get)
  • etc

Like @user3553031 say in comment:

Most likely, those other numbers that you're adding into sum are whatever else is on the call stack -- things like the saved return address and possibly even the current value of sum itself. This is strongly dependent on your operating system, compiler, and machine architecture; C does not define the structure of the call stack or even require that one exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM