Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected behaviour when null pointer given to snprintf

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?

like image 634
greTech Avatar asked Sep 14 '25 13:09

greTech


2 Answers

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.

like image 122
cnicutar Avatar answered Sep 17 '25 03:09

cnicutar


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

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.

like image 39
Mark Amery Avatar answered Sep 17 '25 03:09

Mark Amery