0

For various reasons, I need to format a string of unknown length, then supply that string into a function. I can supply the output string in chunks. This is my idea so far.

void formatToSomeFunction(const char * str_msg, ...){
    int length = 0;    
    char buffer[100];

    va_list args;
    va_start(args, str_msg);

    while(!(length >= 0 && length < 100)){
        length = vsnprintf(buffer,100, str_msg, args);
        some_output_function(buffer,100);
        str_msg += 100;
    }

    va_end(args);
}

Unfortunately, this won't work. vsnprintf gives the length of the string after formatting, and even then I'm not able to determine how many args were used.

Ideally, I'd like to do this without allocating on the heap (I'm constrained by performance and space requirements), but it seems like that's a far-fetched dream, so I'll probably just have a dynamically allocated string that's the size of the output and work with that. (I think I just found a solution while writing this question)

Is there any other way to do this?

ChilliDoughnuts
  • 367
  • 2
  • 13
  • Tip: Don't use "magic constants" like literal `100` in your code. Either use a `#define` or a `const` if you can to represent that so the number has meaning and can be changed easily across all your code, instead of having to keep them all in sync. – tadman Sep 25 '18 at 21:27
  • Near dup: https://stackoverflow.com/questions/3774417/sprintf-with-automatic-memory-allocation – jxh Sep 25 '18 at 22:21

0 Answers0