What is the expected behaviour for this code snippet?
char * aNullPointer = 0;
snprintf (res, 128, "Testing %s null pointer",aNullPointer);
Note that I am deliberately trying to get it to de-reference my null pointer aNullPointer
.
Behaviour 1) res
points to a string "Testing (null) null pointer"
Behaviour 2) Seg Fault
It seems I get differing behaviours depending on my platform. Some snprintf
implementations perform a sanity check, whereas others do not.
What is the most common behaviour?
It's undefined behavior - there's nothing to expect. The fact that some implementations check for NULL
and replace it with "nil" or "null" is just a nicety, you can't rely on it at all.
One caveat to the other answers here: it is permissible to pass a null pointer as the first argument to snprintf
if the second argument (specifying the number of bytes to write) is zero.
From the C11 standard (emphasis mine):
The
snprintf
function is equivalent tofprintf
, except that the output is written into an array (specified by arguments
) rather than to a stream. Ifn
is zero, nothing is written, and s may be a null pointer.
This can be useful to first find out how many bytes snprintf
wants to write in order to allocate a buffer of that size to write to with a second call to snprintf
, as shown at https://stackoverflow.com/a/10388547/1709587.
If n
is nonzero, however, the behaviour is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With