https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78521
Bug ID: 78521 Summary: incorrect byte count in -Wformat-length warning with non-constant width or precision Product: gcc Version: 7.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- The gimple-ssa-sprintf pass doesn't correctly handle non-constant width and precision fields in integer (and likely other) directives. For example, in function f below, the width is unknown but the warning indicates that GCC thinks the function outputs exactly 3 bytes. Worse, in function g, the precision is known to be at least 4 but the return value is folded into a constant 1 by the -fprintf-return-value optimization because GCC fails to take into consideration that the precision can increase the size of output. $ cat b.c && /build/gcc-svn/gcc/xgcc -B /build/gcc-svn/gcc -O2 -S -Wall -fdump-tree-optimized=/dev/stdout b.c char d[2]; int f (int w) { return __builtin_sprintf (d, "%*i", w, 123); } int g (int p) { if (p < 4) p = 4; return __builtin_sprintf (d, "%.*i", p, 1); } b.c: In function āfā: b.c:5:33: warning: ā%*iā directive writing 3 bytes into a region of size 2 [-Wformat-length=] return __builtin_sprintf (d, "%*i", w, 123); ^~~ b.c:5:10: note: format output 4 bytes into a destination of size 2 return __builtin_sprintf (d, "%*i", w, 123); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ;; Function f (f, funcdef_no=0, decl_uid=1796, cgraph_uid=0, symbol_order=1) f (int w) { int _4; <bb 2> [100.0%]: _4 = __builtin_sprintf (&d, "%*i", w_2(D), 123); [tail call] return _4; } ;; Function g (g, funcdef_no=1, decl_uid=1799, cgraph_uid=1, symbol_order=2) g (int p) { <bb 2> [100.0%]: p_6 = MAX_EXPR <p_2(D), 4>; __builtin_sprintf (&d, "%.*i", p_6, 1); return 1; }