4

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?

willcode.co
  • 674
  • 1
  • 7
  • 17

5 Answers5

9

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • I guess I was just thinking that snprintf is supposed to be a `safer` version so it might sanity check for nulls. But of course you are right! – willcode.co Sep 07 '12 at 11:14
2

Undefined behaviour. Don't do it.

glibc will use (null) when passing a NULL pointer to %s though, but don't rely on this feature!

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
1

There is in a sense no expected behavior. In fact, it is explicitly stated in the standard that the behaviour is undefined in quite a wide sense: it can work, it can segfault, it can format your harddrive etc. You should check for NULL pointers yourself.

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
0

If we regard to the Opengroup specification, it seems that there's no defined behaviour for this case:

The argument shall be a pointer to an array of char. Bytes from the array shall be written up to (but not including) any terminating null byte. If the precision is specified, no more than that many bytes shall be written. If the precision is not specified or is greater than the size of the array, the application shall ensure that the array contains a null byte.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Claudi
  • 5,224
  • 17
  • 30