Printing errors in program C

I am trying to port printf to a C program (well, actually _snprintf, but this example is simpler), and it's hard for me to get variable arguments. Here is my code:

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

void works(void)
{
    printf("%d\n", 100);
}

void wrap_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    printf(fmt, args);
    va_end(args);
}

void broken(void)
{
    wrap_printf("%d\n", 100);
}

int main(void)
{
    works();
    broken();
    return 0;
}

Here is my conclusion:

100
3668388

The args variable looks good after a call va_startin my code, but as soon as I enter the C runtime code and they call va_start, the value looks bad. Any thoughts on what I can do wrong?

+5
source share
2 answers
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);

You need to call vprintfinstead printf. Functions v*printfunderstand the arguments va_List. I am surprised that you did not receive a warning.

+9
source

args, va_list, printf(), , , , va_list.

vprintf(), , a va_list, , .

+5

All Articles