为什么这个 GNU C 可变函数 return 是一个巨大的数字?

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

我正在查看 this example 的 C 可变参数函数,写成 GNU.org。我的 OS 是 Debian 8.6。

这是我对它的细微改动,文件名是 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;
}

这是我的 makefile _example.mak:

CFLAGS=-Wall -g
CFILE=ex

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

打开终端时的输出 运行 make -f _example.mak:

./ex
15
55
1141373223
rm -f ex

为什么第三个addEmUp()打印1141373223

你有未定义的行为。

您将 10 作为第一个参数发送,但您调用 addEmUp() 时仅使用了 3 个附加参数。

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

当你有一个未定义的行为时,你无法知道会发生什么。当您的函数 addEmUp()va_arg() 走得太远时。可以引起很多思考:

  • 分段错误
  • 错误的行为(你得到的)
  • 等等

喜欢@user3553031 在评论中说:

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.