Search code examples
cvariadic-functions

Simple Variadic C Function Parameters Error


I have a very simple code. This code working on Linux Machine. But When I build with a Cross Compile and run on a Embbedded Hardware parameter, Values of variadic functions are wrong. Is it about Compiling(Cross Compiling)? All application runnig fine but variadic function not working.

My Sample code below. Both of foo and formatString function working wrong.

void foo(char *fmt, ...)
{
    va_list ap;
    int d;
    char c, *s;

    va_start(ap, fmt);
    while (*fmt)
    {
        switch (*fmt++) 
        {
            case 's' :
                s = va_arg(ap, char *);
                printf("string %s\n", s);
                break;
            case 'd' : 
                d = va_arg(ap, int);
                printf("int %d\n", d);
                break;
            case 'c':               
                c = (char) va_arg(ap, int);
                printf("char %c\n", c);
                break;
       }
   va_end(ap);
}

void formatString(char* format, ...)
{
    va_list args;
    char buffer[100];

    va_start(args, format);
    sprintf(buffer, format, args);
    va_end(args);

    printf((char*)buffer);
}

int main(int argc, char **argv)
{
    printf("\nProgram Started");

    foo("MSG : %d", 10);

    formatString("MSG : %d", 10);

    return 0;
}

Solution

  • Your call to sprintf is incorrect. If you want to pass a va_list into sprintf you should use the vsprintf function.

    Also, to be a little bit safer, consider using snprintf (vsnprintf in this case) instead of sprintf.