g++ + strncat:可能会溢出目标缓冲区
我需要在我的 C++ 程序中包含一个 C 函数,当使用 g++ 编译代码时,我收到以下警告:
In function ‘char* strncat(char*, const char*, size_t)’,
inlined from ‘int get_usage(pid_t, pstat*)’ at src/getusage.c:24:
/usr/include/bits/string3.h:154: warning: call to
char* __builtin___strncat_chk(char*, const char*, long unsigned int,
long unsigned int) might overflow destination buffer
代码:
int pidof(const char* process_name){
char cmd[50] ="pidof ";
strncat(cmd, process_name, sizeof(cmd) - strlen(cmd) -1);
[..]
如何摆脱此警告?
I need to include an C function in my C++ program, when compiling the Code with g++ I get the following warning:
In function ‘char* strncat(char*, const char*, size_t)’,
inlined from ‘int get_usage(pid_t, pstat*)’ at src/getusage.c:24:
/usr/include/bits/string3.h:154: warning: call to
char* __builtin___strncat_chk(char*, const char*, long unsigned int,
long unsigned int) might overflow destination buffer
Code:
int pidof(const char* process_name){
char cmd[50] ="pidof ";
strncat(cmd, process_name, sizeof(cmd) - strlen(cmd) -1);
[..]
How do I get rid of this warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码是安全的(我认为),但是只有当您知道以下内容的长度时,
strncat()
函数才可以安全使用:如果您还知道要添加的材料并且它比可用空间短,您可以简单地使用
memmove()
;如果它更长,您是否应该报告您正在截断它?如果您不知道要添加的材料的长度,也许您应该这样做(这样您就可以报告您正在截断某些内容),但如果这不方便,那么您仍然可以使用memmove()
并在缓冲区末尾添加一个 null 以确保 null 终止。Your code is safe (I think), but the
strncat()
function is only safe to use if you know the length of:If you also know the length of the material to be added and it is shorter than the space available, you can simply use
memmove()
; if it is longer, should you report that you're truncating it; if you don't know the length of the material to be added, maybe you should (so you can report that you're truncating something), but if that's inconvenient, then you can still usememmove()
and add a null at the end of the buffer to ensure null termination.来自发布的评论:
strlcat()
为您正在执行的连接类型提供了一个更简单的接口 - 旨在防止这种类型的错误(忘记考虑缓冲区中已有字符串的长度)。如果你的工具链没有它,OpenBSD 版本有一个相当自由的许可证,如果你出于某种原因无法合并它,那么你自己实现它是一个非常简单的函数(只要确保测试边界条件,如果你走这条路)。执行一次,就可以永远避免由于
strncat()
使用不当而导致的错误。由于strlcat()
使用不当而可能遇到的错误类型可能不太严重(忘记检查截断通常比缓冲区溢出问题要小)。From a comment posted:
strlcat()
presents a more straightforward interface to the kind of concatenation you're performing - designed to prevent exactly this type of error (forgetting to account for the length of the string already in the buffer).If your toolchain doesn't have it, the OpenBSD version has a pretty liberal license, and if you're unable to incorporate that for whatever reason, it's a pretty simple function to implement yourself (just make sure to test the boundary conditions if you go this route). Do this once, and you can avoid bugs caused by improper use of
strncat()
forever. The types of bugs you might run into with improper use ofstrlcat()
are likely to be less severe (forgetting to check for truncation is usually less of a problem than buffer overruns).