GCC 8 添加了 -Wstringop-truncation
警告。来自 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82944 :
GCC 8.0 中通过 r254630 为错误 81117 添加的 -Wstringop-truncation 警告专门用于突出可能意外使用 strncpy 函数,该函数从源字符串中截断终止 NUL 字符。请求中给出的此类滥用的示例如下:
char buf[2];
void test (const char* str)
{
strncpy (buf, str, strlen (str));
}
我收到与此代码相同的警告。
strncpy(this->name, name, 32);
warning: 'char* strncpy(char*, const char*, size_t)' specified bound 32 equals destination size [-Wstringop-truncation`]
Considering that this->name
is char name[32]
and name
is a char*
with a length potentially greater than 32. I would like to copy name
变成 this->name
如果大于32则截断。应该 size_t
是31而不是32?我很困惑。 this->name
不是强制终止的。
原文由 JRR 发布,翻译遵循 CC BY-SA 4.0 许可协议
此消息试图警告您,您正在做的正是您正在做的事情。很多时候,这不是程序员的本意。如果这是您想要的(意思是,您的代码将正确处理字符数组最终不会包含任何空字符的情况),请关闭警告。
如果您不想或无法在全局范围内关闭它,您可以按照@doron 的指示在本地关闭它: