Mark
Mark

Reputation: 6484

vsnprintf and NULL input string argument

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

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

Quoting C11, chapter §7.21.6.12, The vsnprintf function

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). [....]

and then, for snprintf(), §7.21.6.5

[...] If n is zero, nothing is written, and s 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

user6322488
user6322488

Reputation: 116

vsnprintf(NULL, 0, "%d", p); is actually defined behavior.

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

Related Questions