是 snprintf(NULL,0,...);行为规范?

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

在 Linux 它 returns 将打印的字符数。

这是标准化行为吗?

根据 snprintf(3) 它由 POSIX 和 C99 标准化。该手册页还说:

   Concerning the return value of snprintf(), SUSv2 and C99 contradict
   each other: when snprintf() is called with size=0 then SUSv2
   stipulates an unspecified return value less than 1, while C99 allows
   str to be NULL in this case, and gives the return value (as always)
   as the number of characters that would have been written in case the
   output string has been large enough.  POSIX.1-2001 and later align
   their specification of snprintf() with C99.

所以int i=snprintf(NULL, 0, "some-format-string",.... );应该输入i一个负数失败时的数字,或成功时的 non-negative 输出大小。

(我不完全知道如果输出大小大于 INT_MAX 会发生什么,这是 非常 不寻常;我猜它将是一个失败案例)

是的。

来自7.21.6.5的snprintf函数, N1570(C11草案):

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.

这是一种查找未知数据长度的有用方法,您可以先找到所需的长度,然后再分配准确的内存量。一个典型的用例是:

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);