【发布时间】:2015-03-21 17:58:02
【问题描述】:
#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 开发团队报告吗?
【问题讨论】:
-
'charArray'是一个指针,当作为参数传递给函数时,数组衰减为指针。sizeof这里给出指针的大小char* -
@P0W:查看编辑后的代码。
标签: c++ gcc gcc-warning