问题
I've been compiling with clang for a while, but now that I'm back with GCC (8.3), I'm getting a lot of non-fatal warnings.
For example, I have the following line of code that prints a given longitude, in a fixed-width format "(degrees)(minutes).(seconds)(W|E)". Before this, though, I have code that calculates degrees
, minutes
, and seconds
while making sure that all values are sane (e.g., that -90 ≤ degrees
≤ 90 no matter what).
So this compiles and runs perfectly:
snprintf(pResult, 10, "%03d%02u.%02u%c", degrees, minutes, seconds, (degrees < 0 ? 'W' : 'E'));
However, GCC gives a lot of warnings about it:
aprs-wx.c: In function ‘myFunction’:
aprs-wx.c:159:39: warning: ‘%c’ directive output may be truncated writing 1 byte into a region of size between 0 and 2 [-Wformat-truncation=]
snprintf(pResult, 10, "%03d%02u.%02u%c", degrees, minutes, seconds, (decimal < 0 ? 'W' : 'E'));
^~
In file included from /usr/include/stdio.h:867,
from aprs-wx.c:21:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:67:10: note: ‘__builtin___snprintf_chk’ output between 10 and 12 bytes into a destination of size 10
return __builtin___snprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__bos (__s), __fmt, __va_arg_pack ());
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I am fully aware that if my code fails to sanitize inputs, there may be value truncation. How can I disable this warning, or better yet, adjust my code so that GCC won't complain even with -Wall
set?
回答1:
How can I disable this warning, or better yet, adjust my code so that GCC won't complain even with -Wall set?
Use %
to limit widths.
snprintf(pResult, 10, "%03d%02u.%02u%c",
degrees%100, minutes%100u, seconds%100u, (degrees < 0 ? 'W' : 'E'));
// ^ ^
// signed , unsigned
// max 3 characters, max 2 characters
Your result may vary.
来源:https://stackoverflow.com/questions/57936803/gcc-warning-me-about-directive-output-truncation