https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128707
Bug ID: 128707
Summary: wrong code with -fprintf-return-value: "%.*s" with a
precision range including negative values has its
result maximum clamped to the positive precision bound
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: 0599jiangyc at gmail dot com
Target Milestone: ---
The following code:
```c
/* -fprintf-return-value: "%.*s" whose precision argument has a range that
includes negative values (negative precision == no precision) gets the
result upper bound clamped to the positive precision bound.
Godbolt: x86-64 gcc (trunk), flags: -O2
gcc -O1 repro.c && ./a.out (also -O2, -O3; fixed by
-fno-printf-return-value)
Expected: exit 0. GCC trunk (and 11): "FAIL", exit 1. */
#include <stdio.h>
__attribute__((noipa)) int
f (int all)
{
char b[32];
/* -1: print the whole string, 3: at most 3 chars. */
int r = sprintf (b, "%.*s", all ? -1 : 3, "hello");
return r > 3; /* folded to 0 */
}
__attribute__((noipa)) int
g (int all, int k)
{
char b[32];
int r = sprintf (b, "%.*s", all ? -1 : 2, k ? "abcd" : "xyz");
return r > 2; /* folded to 0 (non-constant string branch) */
}
int
main (void)
{
int bad = 0;
if (f (1) != 1)
bad |= 1;
if (g (1, 1) != 1)
bad |= 2;
if (bad)
{
printf ("FAIL %d\n", bad);
return 1;
}
printf ("OK\n");
return 0;
}
```
Resulted in this output:
```
$ gcc -O2 repro.c && ./a.out
FAIL 3
(gcc -O0, -O2 -fno-printf-return-value and clang print OK)
```
Trunk: https://godbolt.org/z/6c537MeEb (x86-64 gcc trunk, -O2, executed;
reproduces as of 2026-11-13; also GCC 14.2 and GCC 11)
Root cause: gcc/gimple-ssa-sprintf.cc, format_string (). set_precision () maps
the precision argument range (here [-1, 3]) through get_int_range (...,
negbound = -1). A negative precision means "no precision", so the whole string
is printed. Even so, both string branches clamp the result maximum to
dir.prec[1] whenever prec[1] >= 0, without checking prec[0] >= 0:
- constant string: `if ((unsigned HOST_WIDE_INT) dir.prec[1] < res.range.max)
res.range.max = dir.prec[1];`
- non-constant string: `else if (dir.prec[1] >= 0) { ... res.range.max =
dir.prec[1]; }`
- the %ls constant branch has the same pattern.
The result range of sprintf (b, "%.*s", all ? -1 : 3, "hello") therefore
becomes [0, 3], and r > 3 is folded to false, although r is 5 when all != 0.
printf ("%.*s", -1, s) meaning "the whole string" is a common idiom. The
floating-point sibling, PR79800, was fixed in format_floating only.
Suggested fix: clamp the maximum (and the likely/unlikely counts) to
dir.prec[1] only when dir.prec[0] >= 0. Otherwise keep the string's maximum
length.