问题描述
GCC 8添加了-Wstringop-truncation
警告.来自 https://gcc.gnu.org/bugzilla/show_bug.cgi?id= 82944 :
GCC 8 added a -Wstringop-truncation
warning. From https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82944 :
char buf[2];
void test (const char* str)
{
strncpy (buf, str, strlen (str));
}
我收到与此代码相同的警告.
I get the same warning with this code.
strncpy(this->name, name, 32);
warning: 'char* strncpy(char*, const char*, size_t)' specified bound 32 equals destination size [-Wstringop-truncation`]
考虑到this->name
是char name[32]
并且name
是char*
,其长度可能大于32.我想将name
复制到this->name
中,如果大于32,则将其截断. .size_t
应该是31而不是32?我很困惑.强制将this->name
终止为NUL.
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
into this->name
and truncate it if it is greater than 32. Should size_t
be 31 instead of 32? I'm confused. It is not mandatory for this->name
to be NUL-terminated.
推荐答案
此消息试图警告您您正在做的事情恰好在做.很多时候,这不是程序员想要的.如果它是您想要的(意味着您的代码将正确处理字符数组最终不会包含任何空字符的情况),请关闭警告.
This message is trying to warn you that you're doing exactly what you're doing. A lot of the time, that's not what the programmer intended. If it is what you intended (meaning, your code will correctly handle the case where the character array will not end up containing any null character), turn off the warning.
如果您不想全局关闭或无法将其关闭,可以按照@doron的说明在本地将其关闭:
If you do not want to or cannot turn it off globally, you can turn it off locally as pointed out by @doron:
#include <string.h>
char d[32];
void f(const char *s) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
strncpy(d, s, 32);
#pragma GCC diagnostic pop
}
这篇关于gcc-8 -Wstringop-truncation有什么好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!