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

Al *_*ndy 0 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
}
Run Code Online (Sandbox Code Playgroud)

使用此命令行在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
Run Code Online (Sandbox Code Playgroud)

根据实际的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.
Run Code Online (Sandbox Code Playgroud)

这应该编译得很好,因为charArray是一个数组!

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

gna*_*729 6

你直接陷入陷阱.

在C,C++,Objective-C,Objective-C++中,具有看起来像"T的数组"的声明的参数实际上具有类型T*.

您的参数charArray有一个看起来像"100个字符数组"的声明,但声明实际上是"指向char的指针".

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

BTW.strncpy使用它的方式非常危险.

  • 好的。这是对我的解释。1)但是我可以修复它吗?2 ) 为什么 strncpy 以这种方式使用它非常危险?是不是因为我不考虑整理`0x00`? (2认同)