GCC警告我指令输出被截断 [英] GCC warning me about directive output truncation
问题描述
我已经用clang编译了一段时间了,但是现在我回到了GCC(8.3),我收到了很多非致命的警告.
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.
例如,我有以下代码行以固定宽度的格式(度)(分钟).(秒)(W | E)"打印给定的经度.不过,在此之前,我有一些代码可以计算度
,分钟
和 seconds
,同时确保所有值都是合理的(例如,-≤90≤ degrees
≤90,无论如何).
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'));
但是,GCC对此发出了很多警告:
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 ());
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我完全知道,如果我的代码未能清理输入,则可能会截断值.我该如何禁用此警告,或者更好地调整我的代码,以使即使设置了 -Wall
,GCC也不会抱怨?
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?
推荐答案
如何禁用此警告,或者更好地调整我的代码,以使即使设置了-Wall,GCC也不会抱怨?
How can I disable this warning, or better yet, adjust my code so that GCC won't complain even with -Wall set?
使用%
限制宽度.
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.
这篇关于GCC警告我指令输出被截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!