Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand snprintf's processing NULL argument?

Tags:

c

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.

like image 907
Nan Xiao Avatar asked Jun 02 '26 22:06

Nan Xiao


1 Answers

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 "[email protected]" 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 "[email protected]" as a valid email address.

like image 141
AnT Avatar answered Jun 05 '26 21:06

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!