gcc-8 -Wstringop-truncation有什么好的做法? [英] gcc-8 -Wstringop-truncation what is the good practice?

查看:1456
本文介绍了gcc-8 -Wstringop-truncation有什么好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 :

在GCC 8.0中通过r254630为错误81117添加的-Wstringop-truncation警告专门用于突出显示strncpy函数的可能意外使用,该函数从源字符串中截断了终止NUL字符.请求中给出的此类滥用示例如下:

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));
}

我收到与此代码相同的警告.

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->namechar name[32]并且namechar*,其长度可能大于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有什么好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆