Search code examples
cstandardsstdio

Is snprintf(NULL,0,...); behavior standardized?


On Linux it returns the number of characters that would be printed.

Is this standardized behavior?


Solution

  • Yes.

    From 7.21.6.5 The snprintf function, N1570 (C11 draft):

    The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

    It's a useful method to find the length of unknown data for which you can first find the necessary length and then allocate the exact amount of memory. A typical use case is:

    char *p;
    
    int len = snprintf(0, 0, "%s %s some_long_string_here_", str1, str2);
    
    p = malloc(len + 1);
    
    snprintf(p, len + 1, "%s %s some_long_string_here", str1, str2);