我收到以下gcc格式 - 截断警告:
test.c:8:33: warning: ‘/input’ directive output may be truncated writing 6 bytes into a region of size between 1 and 20 [-Wformat-truncation=]
snprintf(dst, sizeof(dst), "%s-more", src);
^~~~~~
test.c:8:3: note: ‘snprintf’ output between 7 and 26 bytes into a destination of size 20
snprintf(dst, sizeof(dst), "%s-more", src);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
像这样的代码:
char dst[20];
char src[20];
scanf("%s", src);
snprintf(dst, sizeof(dst), "%s-more", src);
printf("%s\n", dst);
Run Code Online (Sandbox Code Playgroud)
我知道它可能会被截断 - 但这正是我首先使用snprintf的原因.有没有办法让编译器明白这是预期的(不使用编译指示或-Wno格式截断)?
我在古老的 Linux (RedHat 5.2) 和现代 macOS 10.14.6 Mojave 上使用 GCC 9.2.0,并且我在两者上都得到了同样的抱怨。
\n\n#include <stdio.h>\n#include <time.h>\n\nstruct Example\n{\n /* ... */\n char mm_yyyy[8]; /* Can\'t be changed */\n /* ... */\n};\n\nextern void function(struct tm *tm, struct Example *ex);\n\nvoid function(struct tm *tm, struct Example *ex)\n{\n snprintf(ex->mm_yyyy, sizeof(ex->mm_yyyy), "%d-%d",\n tm->tm_mon + 1, tm->tm_year + 1900);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n当使用 和 进行任何优化编译时-Wall(所以不使用-O0也不使用任何优化选项),编译器会说:
$ gcc -O -Wall -c so-code.c \nso-code.c: In function \xe2\x80\x98function\xe2\x80\x99:\nso-code.c:15:49: warning: \xe2\x80\x98%d\xe2\x80\x99 directive output may be truncated writing between 1 …Run Code Online (Sandbox Code Playgroud)