code: =============================== #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *n = "12345"; char c[5] = {0}; strncpy(c, "12345", 5); printf("%s----%c,%c,%c,%c,%c----->\n", c, c[0], c[1], c[2], c[3], c[4]); return 0; } ============================== output: ========================= 1234----1,2,3,4,5-----> ========================= it looks like only happend on version "gcc version 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC) "
%s requires a zero-terminated string.
Right, the test case is invalid. But it would be helpful if GCC issued a warning for it. With optimization, tree-ssa-strlen.c is able to detect that the array created by strncpy isn't NUL-terminated. Printf should be able to use that information to diagnose its use in a %s directive. The latter depends on bug 49905 being resolved in a smart way, and on __builtin_printf being hooked into the strlen optimization. Similarly, other string manipulation functions should be able to detect the same problem (this part is the subject of bug 71296). Since this is related to something I'm investigating I'll take the liberty to confirm this report as an enhancement request for such a warning.
*** Bug 83959 has been marked as a duplicate of this bug. ***
GCC 8 and 9 detect the unterminated strncpy call but not yet passing the result to printf. I'm hoping to do it in GCC 10. $ gcc -O2 -S -Wall pr71501.c pr71501.c: In function ‘main’: pr71501.c:7:9: warning: unused variable ‘n’ [-Wunused-variable] char *n = "12345"; ^ pr71501.c:9:3: warning: ‘strncpy’ output truncated before terminating nul copying 5 bytes from a string of the same length [-Wstringop-truncation] strncpy(c, "12345", 5); ^~~~~~~~~~~~~~~~~~~~~~ GCC 9 detects some very simple cases of passing unterminated arrays to printf: $ cat z.c && gcc -O2 -S -Wall z.c const char a[] = { '1', '2', '3' }; void f (void) { __builtin_printf ("%s", a); } z.c: In function ‘f’: z.c:5:22: warning: ‘%s’ directive argument is not a nul-terminated string [-Wformat-overflow=] 5 | __builtin_printf ("%s", a); | ^~ ~ z.c:1:12: note: referenced argument declared here 1 | const char a[] = { '1', '2', '3' }; | ^
With pr87719 resolved, GCC 10 detects unterminated constant array arguments to printf %s directives, but not the same problem in dynamically constructed arrays. That has to wait until GCC 11. $ cat pr71501.c && gcc -O2 -S -Wall pr71501.c const char a[] = { 'a' }; int main (void) { const char b[] = { 'b' }; __builtin_printf ("a=%s", a); // warning (good) __builtin_printf ("b=%s", b); // missing warning } pr71501.c: In function ‘main’: pr71501.c:7:24: warning: ‘%s’ directive argument is not a nul-terminated string [-Wformat-overflow=] 7 | __builtin_printf ("a=%s", a); // warning (good) | ^~ ~ pr71501.c:1:12: note: referenced argument declared here 1 | const char a[] = { 'a' }; | ^