How to understand snprintf's processing NULL argument?

  • A+
Category:Languages

Check following simple C program:

#include <stdio.h>  int main(void) {     char str[4] = {1, 1, 1, 1};     snprintf(str, sizeof(str), "%s%s", "a", NULL);      printf("%s/n", str);     return 0; } 

Build and run it on Linux:

$ gcc test.c $ ./a.out a(n 

How to understand "(n" characters which come after a in the output? I expect when snprintf come across NULL argument, it will stop processing. BTW, I can't find related information from snprintf manual.

 


If snprintf (fprintf, printf or any function from that family) comes across a null pointer argument for a %s format specifier, the behavior is undefined. In real life instead of crashing or behaving unpredictably many Standard Library implementations prefer to insert a (null) sequence into the recipient buffer. This is what you observe in your experiment - the beginning of that (null) that snprintf managed to fit into the remaining space of that str recipient array.


There was a story a long time ago (even Internet, which never forgets, seems to have forgotten about it), about an ordinary customer of a large US telecommunication company, who registered "null" as his email ID, thus getting "null@company.com" as his email address. Suddenly he started receiving a large amount of internal company's emails containing other customers' personal data. If I remember correctly, it was caused by a bug in internal company's software, where a null pointer was passed to a function responsible for forming the destination email addresses. And that function, instead of crashing, resorted to a similar fail-safe behavior in response to a null-pointer argument. The bug remained unnoticed until someone actually registered "null@company.com" as a valid email address.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: