strncpy doesn't always null-terminate

后端 未结 5 956
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 08:23

I am using the code below:

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


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-18 09:06

    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... */
    }
    

提交回复
热议问题