call printf using va_list

CPrintfVariadic Functions

C Problem Overview


void TestPrint(char* format, ...)
{
    va_list argList;

    va_start(argList, format);
    printf(format, argList);
    va_end(argList);
}


int main()
{
    TestPrint("Test print %s %d\n", "string", 55);
    return 0;
}

I need to get:

Test print string 55

Actually, I get garbage output. What is wrong in this code?

C Solutions


Solution 1 - C

Use vprintf() instead.

Solution 2 - C

Instead of printf, I recommend you try vprintf instead, which was created for this specific purpose:

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

void errmsg( const char* format, ... )
{
    va_list arglist;

    printf( "Error: " );
    va_start( arglist, format );
    vprintf( format, arglist );
    va_end( arglist );
}

int main( void )
{
    errmsg( "%s %d %s", "Failed", 100, "times" );
    return EXIT_SUCCESS;
}

Source

Solution 3 - C

As others have pointed out already: In this case you should use vprintf instead.

But if you really want to wrap printf, or want to wrap a function that does not have a v... version, you can do that in GCC using the non-standard __builtin_apply feature:

int myfunction(char *fmt, ...)
{
    void *arg = __builtin_apply_args();
    void *ret = __builtin_apply((void*)printf, arg, 100);
    __builtin_return(ret);
}

The last argument to __builtin_apply is the max. total size of the arguments in bytes. Make sure that you use a value here that is large enough.

Solution 4 - C

This is not how you use printf(). If you want to use va_lists, use vprintf() instead. Look here for reference.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex FView Question on Stackoverflow
Solution 1 - COliver CharlesworthView Answer on Stackoverflow
Solution 2 - Conteria_View Answer on Stackoverflow
Solution 3 - CCliffordViennaView Answer on Stackoverflow
Solution 4 - CConstantiniusView Answer on Stackoverflow