https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128269
Bug ID: 128269
Summary: wrong code at -O1 and above: snprintf "%lc" with a
wint_t in [0, 200] is assumed not to return a negative
value
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: kyuwoncho18 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
#include <stdio.h>
#include <wchar.h>
volatile int v = 128;
int main(void)
{
char b[32];
int x = v;
if (x < 0 || x > 200)
return 0;
int r = snprintf(b, sizeof b, "%lc", (wint_t)x);
printf("%d %d\n", r, r < 0);
return 0;
}
godbolt: https://godbolt.org/z/7fjdf5TKE
With glibc the startup "C" locale cannot encode the wide character 128 (wcrtomb
fails with EILSEQ), so snprintf returns -1 and the program must print "-1 1",
as it does at -O0 and with -O1 -fno-printf-return-value. At -O1, -O2, -O3 and
-Os it prints "-1 0".