Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strncpy doesn't always null-terminate

Tags:

c

strncpy

I am using the code below:

char filename[ 255 ];
strncpy( filename, getenv( "HOME" ), 235 );
strncat( filename, "/.config/stationlist.xml", 255 );

Get this message:

(warning) Dangerous usage of strncat - 3rd parameter is the maximum number of characters to append.
(error) Dangerous usage of 'filename' (strncpy doesn't always null-terminate it).
like image 278
user1840007 Avatar asked Dec 02 '22 22:12

user1840007


1 Answers

I typically avoid using str*cpy() and str*cat(). You have to contend with boundary conditions, arcane API definitions, and unintended performance consequences.

You can use snprintf() instead. You only have to be contend with the size of the destination buffer. And, it is safer in that it will not overflow, and will always NUL terminate for you.

char filename[255];
const char *home = getenv("HOME");
if (home == 0) home = ".";
int r = snprintf(filename, sizeof(filename), "%s%s", home, "/.config/stationlist.xml");
if (r >= sizeof(filename)) {
    /* need a bigger filename buffer... */
} else if (r < 0) {
    /* handle error... */
}
like image 180
jxh Avatar answered Dec 22 '22 05:12

jxh