Reputation: 6484
What is the expected behavior of vsnprintf
when it has an input NULL string and/or size=0, e.g.
vsnprintf(NULL, 0, "%d", p);
or
vsnprintf(NULL, 10, "%d", p);
Is it undefined behavior or valid scenario? It doesn't crash with both input string as NULL
and its length as 0
, and returns -1 (the same for valid non-NULL string and zero length), however it does crash the other way around (NULL
input string and positive length).
Upvotes: 7
Views: 3868
Reputation: 134356
Quoting C11, chapter §7.21.6.12, The vsnprintf
function
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). [....]
and then, for snprintf()
, §7.21.6.5
[...] If
n
is zero, nothing is written, ands
may be a null pointer.
So, your first case is defined, while the second case invokes undefined behavior by attempting to access an invalid (NULL
) pointer.
Upvotes: 2
Reputation: 116
vsnprintf(NULL, 0, "%d", p);
is actually defined behavior.
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);
is not. Since n
is not zero, you've violated a constraint and you got undefined behavior. Either way, you're likely writing to deference a NULL pointer which is again undefined behavior. If you're lucky your program crashes. If you're not, it'll keep running and do weird things to your program.
Upvotes: 6