Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 937
Mark Avatar asked May 11 '16 21:05

Mark


2 Answers

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.

like image 70
user6322488 Avatar answered Sep 19 '22 10:09

user6322488


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.

like image 36
Sourav Ghosh Avatar answered Sep 21 '22 10:09

Sourav Ghosh