C print argument list using va_list

I have a simple argument list. And I just want to print it to stdout, but I get wired output before printing "end". Does anyone know where this empty string and unreadable characters come from

output:

start
hello
hello2
hello3
hello 4

UH  AWAVAUATE1 S1 H  HH E 
end



void printTest(const char* msg, ...) {

    va_list ap;
    int i;
    const char* curMsg=0;
    va_start(ap, msg);
    printf("start\n");

    for(curMsg= msg ;  curMsg!=0 ; curMsg = va_arg(ap,  const char*)){
        printf("%s\n", curMsg);
    }
    printf("end\n");
    va_end(ap);
}



int main(){

    printTest("hello", "hello2", "hello3", "hello 4");
    return 0;
}
+3
source share
2 answers

How do you expect to read a null pointer to end a loop when you don't pass it? Change the call to:

printTest("hello", "hello2", "hello3", "hello 4", (char *)0);
+5
source

The va_list is not NULL terminated. In fact, it does not provide any information about how many arguments exist. Your arguments should indicate how many arguments exist. For example, with printf (), a format argument indicates the number of additional arguments to process.

NULL- , NULL .

+4

All Articles