vsnprintf 和 NULL 输入字符串参数
vsnprintf and NULL input string argument
当输入 NULL 字符串 and/or size=0 时,vsnprintf
的预期行为是什么,例如
vsnprintf(NULL, 0, "%d", p);
或
vsnprintf(NULL, 10, "%d", p);
它是未定义的行为还是有效的场景?它不会因输入字符串为 NULL
及其长度为 0
和 returns -1(对于有效的非 NULL 字符串和零长度相同)而崩溃,但它确实如此反过来崩溃(NULL
输入字符串和正长度)。
引用 C11,章节 §7.21.6.12,vsnprintf
函数
The vsnprintf
function is equivalent to snprintf
, with the variable argument list
replaced by arg
, which shall have been initialized by the va_start
macro (and possibly subsequent va_arg
calls). [....]
然后,对于 snprintf()
,§7.21.6.5
[...] If n
is zero, nothing is written, and s
may be a null pointer.
因此,您的第一个案例已定义,而第二个案例通过尝试访问无效 (NULL
) 指针来调用 undefined behavior。
vsnprintf(NULL, 0, "%d", p);
实际上是定义的行为。
7.19.6.5/2 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. ...
7.19.6.12/2 The vsnprintf
function is equivalent to snprintf
...
vsnprintf(NULL, 10, "%d", p);
不是。由于 n
不为零,因此您违反了约束并且出现了未定义的行为。无论哪种方式,您都可能会写信来引用 NULL 指针,这又是未定义的行为。如果你幸运的话,你的程序会崩溃。如果你不是,它会保留 运行 并对你的程序做一些奇怪的事情。
当输入 NULL 字符串 and/or size=0 时,vsnprintf
的预期行为是什么,例如
vsnprintf(NULL, 0, "%d", p);
或
vsnprintf(NULL, 10, "%d", p);
它是未定义的行为还是有效的场景?它不会因输入字符串为 NULL
及其长度为 0
和 returns -1(对于有效的非 NULL 字符串和零长度相同)而崩溃,但它确实如此反过来崩溃(NULL
输入字符串和正长度)。
引用 C11,章节 §7.21.6.12,vsnprintf
函数
The
vsnprintf
function is equivalent tosnprintf
, with the variable argument list replaced byarg
, which shall have been initialized by theva_start
macro (and possibly subsequentva_arg
calls). [....]
然后,对于 snprintf()
,§7.21.6.5
[...] If
n
is zero, nothing is written, ands
may be a null pointer.
因此,您的第一个案例已定义,而第二个案例通过尝试访问无效 (NULL
) 指针来调用 undefined behavior。
vsnprintf(NULL, 0, "%d", p);
实际上是定义的行为。
7.19.6.5/2 The
snprintf
function is equivalent tofprintf
, except that the output is written into an array (specified by arguments
) rather than to a stream. If n is zero, nothing is written,ands
may be a null pointer. ...7.19.6.12/2 The
vsnprintf
function is equivalent tosnprintf
...
vsnprintf(NULL, 10, "%d", p);
不是。由于 n
不为零,因此您违反了约束并且出现了未定义的行为。无论哪种方式,您都可能会写信来引用 NULL 指针,这又是未定义的行为。如果你幸运的话,你的程序会崩溃。如果你不是,它会保留 运行 并对你的程序做一些奇怪的事情。