当不使用字符串操作时,GCC 11 给出 -Wstringop-overflow

2024-02-21

这是我的代码。

// test.c
#include <stdio.h>

#define ARRAY_SIZE 4

struct example_t {
  int field0;
  int field1;
  int field2;
  int field3;
  int field4;
};

struct example_t func(int *in, int array[ARRAY_SIZE]) {
  struct example_t out;
  return out;
}

int main() {
  int array[ARRAY_SIZE] = { 0, 0, 0, 0 };
  int a = 0;
  struct example_t col = func(&a, array);
  return 0;
}

gcc11.1.0 给了

$ gcc test.c -o test
test.c: In function ‘main’:
test.c:22:26: warning: ‘func’ accessing 16 bytes in a region of size 4 [-Wstringop-overflow=]
   22 |   struct example_t col = func(&a, array);
      |                          ^~~~~~~~~~~~~~~
test.c:22:26: note: referencing argument 2 of type ‘int *’
test.c:14:18: note: in a call to function ‘func’
   14 | struct example_t func(int *in, int array[ARRAY_SIZE]) {
      |                  ^~~~

but g++ didn't.

我不明白为什么会出现警告消息,因为我的代码中没有字符串操作,而且我从未阅读过array in func.

如果只有 4 个或更少的字段struct example_t,GCC不会抱怨。有人可以解释一下为什么这条消息在这里以及我该如何修复它吗?

先感谢您。


看起来警告与这行代码有关:

struct example_t col = func(&a, array);

即使您没有执行任何字符串操作,编译器也会向您发出警告,因为它发现您正在将 int 数组 (array) 传递给需要 int 数组参数的函数 (func)。该警告表明函数 func 可能会访问比为数组参数分配的内存更多的内存。在这种情况下,编译器将数组参数视为可能被不正确访问的潜在缓冲区。

您可以更改函数签名:

如果您的函数 func 实际上并不对字符串进行操作或需要类似字符串的缓冲区,您可以更改其签名以阐明其意图:

struct example_t func(int *in, int array[ARRAY_SIZE]) {
    struct example_t out;
    // Function code
    return out;
}

需要明确的是,这是替换 main.c 文件中有问题的行。

通过明确 func 需要一个整数数组,您可以防止编译器发出警告。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当不使用字符串操作时,GCC 11 给出 -Wstringop-overflow 的相关文章

随机推荐