gcc 4.9.2 -Werror=sizeof-pointer-memaccess 错误?

gcc 4.9.2 bug in -Werror=sizeof-pointer-memaccess?

#include <string.h>

void test(char charArray [100])
{
    strncpy(charArray, "some text", sizeof(charArray));
}

int main()
{
    char charArray [100];
    test(charArray);
    // EDIT: According to comment from P0W I added this line - where is the difference?
    strncpy(charArray, "some text", sizeof(charArray)); // compiles OK
}

使用此命令行在 SLES 11 SP2 上使用 gcc 4.9.2 编译 g++ gcc-warning-bug-2.cpp -Wall -Wextra -c -Werror 我收到此警告。由于 -Werror 标志,我无法编译项目:

gcc-warning-bug-2.cpp: In function ‘void test(char*)’:
gcc-warning-bug-2.cpp:5:40: error: argument to ‘sizeof’ in ‘char* strncpy(char*, const char*, size_t)’ call is the same expression as the destination; did you mean to provide an explicit length? [-Werror=sizeof-pointer-memaccess]
  strncpy(charArray, "some text", sizeof(charArray));
                                        ^
cc1plus: all warnings being treated as errors

根据实际的 gcc 4.9.2 文档 https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

-Wsizeof-pointer-memaccess
Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof.
This warning warns e.g. about memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix, or about memcpy (&foo, ptr, sizeof (&foo));. This warning is enabled by -Wall.

这应该可以正常编译,因为 charArray 是一个数组!

错误?我应该向 GNU gcc 开发团队报告吗?

你直接掉进陷阱了。

在C、C++、Objective-C、Objective-C++中,一个声明看起来像"array of T"的参数实际上具有类型T*。

您的参数 charArray 有一个看起来像 "array of 100 chars" 的声明,但实际上是 "pointer to char"。

因此,strncpy 的第三个参数的值(很可能)为 4 或 8,而不是您似乎期望的 100。

顺便说一句。 strncpy 的使用方式非常危险。