https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86428
Bug ID: 86428 Summary: strlen of const array initialized with a string of the same length not folded Product: gcc Version: 9.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- GCC folds strlen() calls with constant array arguments initialized with strings fewer elements than the size of the array, but not those initialized with strings with either a) the same number of elements or b) more. (a) is a missing optimization opportunity, (b) results in unsafe code (reading past the end of the array). Clang folds all three kinds of strlen calls. $ cat c.c && gcc -O2 -S -Wall -Wextra -fdump-tree-strlen=/dev/stdout c.c const char a[4] = "123"; int f (void) { return __builtin_strlen (a); // folded } const char b[4] = "123\0"; // no warning int g (void) { return __builtin_strlen (b); // not folded } ;; Function f (f, funcdef_no=0, decl_uid=1899, cgraph_uid=1, symbol_order=1) f () { <bb 2> [local count: 1073741825]: return 3; } ;; Function g (g, funcdef_no=1, decl_uid=1903, cgraph_uid=2, symbol_order=3) g () { long unsigned int _1; int _3; <bb 2> [local count: 1073741825]: _1 = __builtin_strlen (&b); _3 = (int) _1; return _3; }