1

People say use vprintf instead of printf. But I can't because I need to use a function of my own.

  • I have 2 custom functions
  • both use va_list
  • one function uses the other function

So is it possible to chain the va_list calls without having those v... functions ? And how ?


Code:
char* createString(const char* line, ...)
{
    char* result = (char*)malloc(100);
    va_list args;
    va_start(args, line);
    vsprintf(result, line, args);
    va_end(args);
    return result;
}

void show(const char* line, ...)
{
    va_list args;
    va_start(args, line);
    char* a = createString(line, args);
    va_end(args);

    AfxMessageBox(a);
    free(a);
}

// usage:
show("test %i, %i", 12, 123);

When I try this I get wrong strings displayed. Instead of 12 and 123 I get some pointers or stuff.

Sad solution:

char* vCreateString(const char* line, va_list args)
{
    char* result = (char*)malloc(100);
    vsprintf(result, line, args);
    return result;
}
Bitterblue
  • 13,162
  • 17
  • 86
  • 124

1 Answers1

2

No, it's not possible. That's why the v-versions exist in the first place, to support passing on a va_list.

You need to make createString() accept a va_list argument.

Also, please don't cast the return value of malloc() in C, and consider using vsnprintf() to protect against buffer overflow.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606