https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113277
Bug ID: 113277 Summary: RFE: analyzer diagnose allocation error leading to pass NULL to snprintf Product: gcc Version: 13.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: aldot at gcc dot gnu.org Target Milestone: --- Currently the analyzer does not diagnose passing in NULL as first argument to snprintf when NULL might stem from an unchecked allocation error. See the undiagnosed occurrence in nak() here: $ cat ~/gcc-alloc-vs-snprintf.c; echo EOF #include <stdio.h> #include <stdlib.h> #if 0 //snprintf first argument can be NULL according to POSIX, so we cannot extern int snprintf (char *__restrict __s, size_t __maxlen, const char *__restrict __format, ...) __THROWNL __attribute__ ((__format__ (__printf__, 3, 4),__nonnull__ ((1)))); #endif /* pass NULL as first arg to snprintf */ int by_arg (void) { int ret = snprintf (NULL, 42, "%d%s", 1234, "mystring"); if (ret != 12) { __builtin_abort (); } return 0; } /* pass NULL via variable as first arg to snprintf */ int by_var (void) { char *chp = NULL; int ret = snprintf (chp, 42, "%d%s", 1234, "mystring"); if (ret != 12) { __builtin_abort (); } return 0; } /* pass NULL on allocation failure as first arg to snprintf */ int nak (void) { char *chp = calloc (42, sizeof(unsigned char)); // chp != NULL not checked here int ret = snprintf (chp, 42, "%d%s", 1234, "mystring"); if (ret != 12) { __builtin_abort (); } return 0; } EOF Gives: $ gcc -std=c11 -W -Wall -Wextra -pedantic -O2 -fanalyzer -c -o /tmp/foo.o gcc-alloc-vs-snprintf.c gcc-alloc-vs-snprintf.c: In function ‘by_arg’: gcc-alloc-vs-snprintf.c:12:13: warning: null destination pointer [-Wformat-truncation=] 12 | int ret = snprintf (NULL, 42, "%d%s", 1234, "mystring"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ gcc-alloc-vs-snprintf.c: In function ‘by_var’: gcc-alloc-vs-snprintf.c:12:13: warning: null destination pointer [-Wformat-truncation=] 12 | int ret = snprintf (NULL, 42, "%d%s", 1234, "mystring"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I would have hoped that in nak() it is noted that the return value of calloc() was not checked before being passed to snprintf and hence might be NULL (even though the size argument was non-zero).