使用 gcc 8.2.1 时出现 strncat Wformat 溢出警告
strncat Wformat-overflow warning when using gcc 8.2.1
我正在使用 gcc 8.2.1 并尝试构建此代码:
std::string dir = "Documents";
char * _tempname = static_cast <char*> (malloc( dir.length() + 14));
strncpy (_tempname, dir.c_str(), dir.length()+1 );
strncat (_tempname, "/hellooXXXXXX", 13);
但它给了我这个警告:
warning: 'char* strncat(char*, const char*, size_t)'
specified bound
13 equals source length [-Wstringop-overflow=]
搜索后,我发现 size_t 等于源长度是一个溢出问题,根据此 link 中的讨论,但我不明白为什么这被认为是一个问题,并且为什么这会溢出目的地。以及如何在不更改代码的情况下删除此警告?
该函数需要目标中剩余的 space 而不是源字符串的长度,因此使用
// ...
strncat(_tempname, "/hellooXXXXXX", dir.length() + 14 - strlen(_tempname) - 1);`
相反。不,忘了那个。请改用 std::string
。
显然 GCC 理解 strncat(_tempname, "/hellooXXXXXX", 13);
与 strcat(_tempname, "/hellooXXXXXX");
没有区别,并且怀疑您使用的是前者而不是后者。
如果您可以更改代码,请改用 strcat
(或者更好,重写代码以使用 std::string
)。
如果您无法更改代码,请使用 -Wno-stringop-overflow
标志来禁用警告。
我的理解是 gcc 发出此警告只是因为用户将边界设置为等于 src 长度是一个常见的错误,仅此而已。
我正在使用 gcc 8.2.1 并尝试构建此代码:
std::string dir = "Documents";
char * _tempname = static_cast <char*> (malloc( dir.length() + 14));
strncpy (_tempname, dir.c_str(), dir.length()+1 );
strncat (_tempname, "/hellooXXXXXX", 13);
但它给了我这个警告:
warning:
'char* strncat(char*, const char*, size_t)'
specified bound 13 equals source length [-Wstringop-overflow=]
搜索后,我发现 size_t 等于源长度是一个溢出问题,根据此 link 中的讨论,但我不明白为什么这被认为是一个问题,并且为什么这会溢出目的地。以及如何在不更改代码的情况下删除此警告?
该函数需要目标中剩余的 space 而不是源字符串的长度,因此使用
// ...
strncat(_tempname, "/hellooXXXXXX", dir.length() + 14 - strlen(_tempname) - 1);`
相反。不,忘了那个。请改用 std::string
。
显然 GCC 理解 strncat(_tempname, "/hellooXXXXXX", 13);
与 strcat(_tempname, "/hellooXXXXXX");
没有区别,并且怀疑您使用的是前者而不是后者。
如果您可以更改代码,请改用 strcat
(或者更好,重写代码以使用 std::string
)。
如果您无法更改代码,请使用 -Wno-stringop-overflow
标志来禁用警告。
我的理解是 gcc 发出此警告只是因为用户将边界设置为等于 src 长度是一个常见的错误,仅此而已。