Search code examples
cprintf

How to calculate the length of output that sprintf will generate?


Goal: serialize data to JSON.

Issue: i cant know beforehand how many chars long the integer is.

i thought a good way to do this is by using sprintf()

size_t length = sprintf(no_buff, "{data:%d}",12312);
char *buff = malloc(length);
snprintf(buff, length, "{data:%d}",12312);
//buff is passed on ...

Of course i can use a stack variable like char a[256] instead of no_buff.

Question: But is there in C a utility for disposable writes like the unix /dev/null? Smth like this:

#define FORGET_ABOUT_THIS ...
size_t length = sprintf(FORGET_ABOUT_THIS, "{data:%d}",12312);

p.s. i know that i can also get the length of the integer through log but this ways seems nicer.


Solution

  • Since C is where simple language, there is no such thing as "disposable buffers" -- all memory management are on programmers shoulders (there is GNU C compiler extensions for these but they are not standard).

    cant know beforehand how many chars long the integer is.

    There is much easier solution for your problem. snprintf knows!

    On C99-compatible platforms call snprintf with NULL as first argument:

    ssize_t bufsz = snprintf(NULL, 0, "{data:%d}",12312);
    char* buf = malloc(bufsz + 1);
    snprintf(buf, bufsz + 1, "{data:%d}",12312);
    
    ...
    
    free(buf);
    

    In older Visual Studio versions (which have non-C99 compatible CRT), use _scprintf instead of snprintf(NULL, ...) call.