GCC warning me about directive output truncation

白昼怎懂夜的黑 提交于 2021-01-27 12:36:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!