Something about va_list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include<stdarg.h>
void test(int args_num,...);
int main()
{
    test(3,"Test1","Test2","Test3");
    test(3,"Test4","test5");
    return 0;
}

void test(int arg_num,...)
{
    int i;
    va_list marker;
    va_start(marker,arg_num);
    for(i=0; i<arg_num; i++)
    {
        printf("%s ",va_arg(marker,const char *));
    }
    printf("\n");
}

I don't understand how the test function works.even if the argument list doesn't enough for three, it still output the first calling's third parameter.
Last edited on
Your example has undefined behaviour on the second call to test when trying to print the undefined third string.
That was not the problem,I mean that after the first calling, it works well ,and it prints Test1 Test2 Test3, and then I try to make some change ,I intended to make the arg_num to be 3; and it prints Test4 Test5 Test3,Test4 and Test5 seems to be reasonable, but why Test3? it seems that va_list is static.
Last edited on
closed account (1vRz3TCk)
You are using the same area of the stack for the second call as the first. The function blindly grabs the next available string to print.

If you call with test(3,"Some longer string","Another Long string"); you will get a different third string (or a crash, or some other undefined behaviour).
I tryed it, no crash happened,it prints "Sone longer string" and "Another Long string" "Test3",it seems nothing changed.
closed account (1vRz3TCk)
That would come under 'some other undefined behaviour'. ;0)

The point is we can't tell you why it is doing what it is doing because the standard does not say what should happen in this case so the compiler implementors do what they think is best. I put your code into VS2010 and got '(null)' as the third string.
It's also leaking resources. You must call va_end on any va_list that va_start was called on. FYI, there is a printf that takes a va_list (vprintf).
http://cplusplus.com/reference/clibrary/cstdio/vprintf/

(It's also discarding the return value of the printf calls.)
It is because of compiler's different implemention,MinGW shows the result that happened on my computer, and the code cann't running on VS2010.
You really want to write programs that are deterministic. That's really why your program is not portable.
Topic archived. No new replies allowed.