我收到以下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);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

在这样的代码上:
char dst[20];
char src[20];
scanf("%s", src);
snprintf(dst, sizeof(dst), "%s-more", src);
printf("%s\n", dst);

我知道它可能会被截断-但这恰恰是我首先使用snprintf的原因。有没有一种方法可以使编译器清楚这是预期的(不使用编译指示或-Wno-format-truncation)?

最佳答案

  • 警告已侵入gcc7.1,请参阅gcc7.1 release changes
  • 来自gcc docs:


  • 问题是bug report,已作为NOTABUG关闭:


  • 但是我们可以只检查snprintf的返回值,该值在错误时返回负值。

  • #include <stdio.h>
    #include <stdlib.h>
    void f(void) {
        char dst[2], src[2];
        // snprintf(dst, sizeof(dst), "%s!", src);
    
        int ret = snprintf(dst, sizeof(dst), "%s!", src);
        if (ret < 0) {
             abort();
        }
    
        // But don't we love confusing one liners?
        for (int ret = snprintf(dst, sizeof(dst), "%s!", src); ret < 0;) exit(ret);
        // Can we do better?
        snprintf(dst, sizeof(dst), "%s!", src) < 0 ? abort() : (void)0;
        // Don't we love obfuscation?
    #define snprintf_nowarn(...) (snprintf(__VA_ARGS__) < 0 ? abort() : (void)0)
        snprintf_nowarn(dst, sizeof(dst), "%s!", src);
    }
    

    使用gcc7.1 gcc7.1 gcc7.2 gcc7.3 gcc8.1和-O{0,1,2,3} -Wall -Wextra -pedantichttps://godbolt.org/上进行了测试。不发出任何警告。 gcc8.1优化/删除对abort()的调用,其优化程度大于-O1

    关于c - 如何在GCC中规避格式截断警告?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51534284/

    10-09 13:12