gpt4 book ai didi

c++ - gcc-8 -Wstringop-truncation 什么是好的做法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:45 27 4
gpt4 key购买 nike

GCC 8 添加了一个 -Wstringop-truncation 警告。来自 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82944 :

The -Wstringop-truncation warning added in GCC 8.0 via r254630 for bug 81117 is specifically intended to highlight likely unintended uses of the strncpy function that truncate the terminating NUL charcter from the source string. An example of such a misuse given in the request is the following:

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`]

考虑到 this->namechar name[32]name 是一个 char*长度可能大于 32。我想将 name 复制到 this->name 中,如果它大于 32,则将其截断。应该 size_t 是 31 而不是 32?我很困惑。 this->name 不是必须以 NUL 结尾的。

最佳答案

此消息试图警告您,您正在做您正在做的事情。很多时候,这不是程序员想要的。如果这是您想要的(意思是,您的代码将正确处理字符数组最终不包含任何空字符的情况),请关闭警告。

如果你不想或不能全局关闭它,你可以像@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
}

关于c++ - gcc-8 -Wstringop-truncation 什么是好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198319/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com