strncpy doesn't always null-terminate

后端 未结 5 961
伪装坚强ぢ
伪装坚强ぢ 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:53

    man strncpy has this to say:

    Warning: If there is no null byte among the first n bytes
    of src, the string placed in dest will not be null terminated.
    

    If it encounters the 0 byte in the source before it exhausts the maximum length, it will be copied. But if the maximum length is reached before the first 0 in the source, the destination will not be terminated. Best to make sure it is yourself after strncpy() returns...

提交回复
热议问题