GCC silently accepts array declarations with string initializers that contain an extra element (the terminating nul) that doesn't fit into the array, and also silently allows such arrays to be used as arguments to functions that require string arguments. It would be helpful to diagnose the initialization. Regardless of diagnostics for those, GCC should also diagnose uses of such arrays when possible (e.g., in the constant cases). This should be done regardless of the form of the initialization (i.e., using a string literal or using a series of characters, as in const char a[3] = { '1', '2', '3' };). const char a[3] = "123"; // no warning int f (void) { return __builtin_strlen (a); // missing warning } void g (char *d) { __builtin_strcpy (d, a); // missing warning }
I have a simple solution for strlen.
Created attachment 44407 [details] Preliminary patch. Lightly tested patch to apply on top of the one for bug 86532.
Patch: https://gcc.gnu.org/ml/gcc-patches/2018-07/msg01124.html
Hmm, I wonder if it would be better to diagnose strlen(a) if a is declared as const char a[] = { 1,2,3 } regardless of if it contains 0 at the end? or just imagine const char a[] = { '%', 'd', '\0' } printf(a, x); this is insane code, no matter if it is zero-terminated.
Yes, that's also (partly) why I submitted a solution for pr71625 comment 15: https://gcc.gnu.org/ml/gcc-patches/2018-07/msg01884.html With that patch applied as well the strlen call is diagnosed.
The warning has been implemented in GCC 9 via r264585 (strlen), r264327 (strcpy), and r264822 (sprintf).