0

I'm trying to encapsulate sprintf call in C function with variable number of arguments. The reason is that I want to have a log wrapper to send log via network in JSON format, instead of writing to console. And I don't want to call sprintf before every log call, but rather pass format and arguments as in sprintf function itself.

I followed this question How to pass variable number of arguments to printf/sprintf and I got string in format parameter working correctly, but number arguments printed with %i somehow printed wrong.

For example:

instead of 40 I get 1073546032 printed

instead of 0 I get 1073545776 printed

If I do sprintf before calling my log function, I see correct numbers in the result string.

Here's my code, but it's exactly same as in other similar question:

void write_log(const char* format, ...)
{
    char formatted_string[256];

    va_list argptr;
    va_start(argptr, format);
    int len = sprintf(formatted_string, format, argptr);
    va_end(argptr);

    // formatted_string sent to JSON builder
}
zmechanic
  • 1,842
  • 21
  • 27
  • 4
    `sprintf()` takes the actual argument not a `va_list`. Have you tried using `vsprintf()` instead? – Allan Wind Apr 02 '23 at 22:29
  • 2
    "I followed [this question](https://stackoverflow.com/questions/1056411/how-to-pass-variable-number-of-arguments-to-printf-sprintf) ...": you didn't really, because those answers all use `vsprintf`. – Nate Eldredge Apr 02 '23 at 22:33
  • @NateEldredge yes, you are right, it seems I completely ignored `v` prefix – zmechanic Apr 03 '23 at 17:57

1 Answers1

1

You have to use vsprintf. (But you should really use vsnprintf instead so that you don't risk overflowing your buffer.)

All the *printf functions come in a v version that takes a va_list instead of variadic arguments.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82