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

时间:2015-03-21 17:58:03

标签: c++ gcc gcc-warning

#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
}

使用此命令行g++ gcc-warning-bug-2.cpp -Wall -Wextra -c -Werror在SLES 11 SP2上使用gcc 4.9.2编译我收到此警告。由于-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开发团队报告吗?

1 个答案:

答案 0 :(得分:5)

你直接陷入陷阱。

在C,C ++,Objective-C,Objective-C ++中,一个参数的声明类似于&#34; T&#34;实际上有T *类型。

你的参数charArray有一个看起来像&#34; 100个字符和#34;的数组的声明,但声明实际上是&#34;指向char&#34;的指针。

因此,strncpy的第三个参数的值(最有可能)为4或8,而不是您似乎要求的100。

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