strncpy doesn't always null-terminate

后端 未结 5 954
伪装坚强ぢ
伪装坚强ぢ 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 08:57

    You may overflow filename with your strncat call.

    Use:

    strncat(filename, "/.config/stationlist.xml",
            sizeof filename - strlen(filename) - 1);
    

    Also be sure to null terminate your buffer after strncpy call:

    strncpy( filename, getenv( "HOME" ), 235 );
    filename[235] = '\0';
    

    as strncpy does not null terminate its destination buffer if the length of the source is larger or equal than the maximum number of character to copy.

提交回复
热议问题