[Bug rtl-optimization/87096] "Optimised" snprintf is not POSIX conformant

bugdal at aerifal dot cx gcc-bugzilla@gcc.gnu.org
Wed Dec 12 17:58:00 GMT 2018


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87096

--- Comment #6 from Rich Felker <bugdal at aerifal dot cx> ---
I don't see how the POSIX requirement makes the function safer. On the
contrary, it makes it less safe by introducing failure cases (that an
application might fail to check for, assuming it knows it has a good
implementation, with no spurious failures) for calls that should no fail. For
example:

char foo[3];
snprintf(buf, size, "%d", 42);
strcpy(foo, buf);

Assuming snprintf succeeds, the strcpy is safe. If snprintf spuriously fails,
buf contains whatever it previously held, possibly uninitialized data, and the
strcpy produces dangerous undefined behavior/overflows.

This is a stupid constructed example, but there are lots of cases where an
application might not check the result of snprintf because it's happy with
truncation and because the format string lacks anything that could fail (like
wchar_t conversions which can fail from EILSEQ), but where it would not be
happy/safe with uninitialized or stale data.


More information about the Gcc-bugs mailing list