开发者

g++ + strncat: might overflow destination buffer

开发者 https://www.devze.com 2023-01-30 08:47 出处:网络
I ne开发者_JAVA技巧ed to include an C function in my C++ program, when compiling the Code with g++ I get the following warning:

I ne开发者_JAVA技巧ed 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?


Your code is safe (I think), but the strncat() function is only safe to use if you know the length of:

  1. the buffer
  2. the material already in the buffer

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 use memmove() and add a null at the end of the buffer to ensure null termination.


From a comment posted:

the error were on another strncat use where I only passed the size of the buffer as size parameter => fixed

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 of strlcat() are likely to be less severe (forgetting to check for truncation is usually less of a problem than buffer overruns).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号