strncpy并不总是空终止

use*_*007 4 c strncpy

我使用下面的代码:

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

收到此消息:

(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).
Run Code Online (Sandbox Code Playgroud)

jxh*_*jxh 6

我通常会避免使用str*cpy()str*cat().您必须应对边界条件,神秘的API定义以及意外的性能影响.

你可以snprintf()改用.您只需要与目标缓冲区的大小竞争.而且,它更安全,它不会溢出,并将永远NUL终止你.

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... */
}
Run Code Online (Sandbox Code Playgroud)


oua*_*uah 5

filename您的呼叫可能会溢出strncat

使用:

strncat(filename, "/.config/stationlist.xml",
        sizeof filename - strlen(filename) - 1);
Run Code Online (Sandbox Code Playgroud)

还要确保在调用后以 null 终止缓冲区strncpy

strncpy( filename, getenv( "HOME" ), 235 );
filename[235] = '\0';
Run Code Online (Sandbox Code Playgroud)

strncpy如果源的长度大于或等于要复制的最大字符数,则as不会以 null 终止其目标缓冲区。