本文介绍了如何在GCC中规避格式截断警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下gcc格式截断警告:

I'm getting the following gcc format-truncation warning:

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)?

I'm aware that it might be truncated - but this is exactly the reason why I'm using snprintf in the first place. Is there a way how to make it clear to the compiler that this is intended (without using a pragma or -Wno-format-truncation)?

推荐答案

  1. 警告已侵入gcc7.1,请参阅 gcc7.1版本更改.
  2. 来自 gcc文档:
  1. warning has been intruded in gcc7.1, see gcc7.1 release changes.
  2. From gcc docs:
  1. 问题出在错误报告,并以NOTABUG的形式关闭:
  1. The issue was a bug report and was closed as NOTABUG:
  1. 但是我们只需要检查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.2 gcc7.3 gcc8.1在 https://godbolt.org/上进行了测试用-O{0,1,2,3} -Wall -Wextra -pedantic.不发出任何警告. gcc8.1优化/删除对abort()的调用,优化程度大于-O1.

Tested on https://godbolt.org/ with gcc7.1 gcc7.2 gcc7.3 gcc8.1 with -O{0,1,2,3} -Wall -Wextra -pedantic. Gives no warning whatsoever. gcc8.1 optimizes/removes the call to abort() with optimization greater then -O1.

这篇关于如何在GCC中规避格式截断警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 18:35