函数strncpy并不总是空终止 [英] strncpy doesn't always null-terminate

查看:487
本文介绍了函数strncpy并不总是空终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code:

 字符文件名[255];
函数strncpy(文件名,GETENV(HOME),235);
strncat函数(文件名,/.config/stationlist.xml,255);

得到这个消息:

 (警告)strncat函数的用法危险 - 第三个参数是字符追加的最大数量。
(错误)文件名的危险使用(函数strncpy并不总是以空值终止)。


解决方案

我通常避免使用 STR * CPY() STR *猫( )。您有边界条件,晦涩难懂的API定义,意外性能结果抗衡。

您可以使用的snprintf()来代替。你只需要与目标缓冲区的大小抗衡。而且,它是因为它不会溢出安全,而且将永远NUL终止你。

 字符文件名[255];
为const char *首页= GETENV(HOME);
如果(家庭== 0)=家。
INT R =的snprintf(文件名,sizeof的(文件名),%s%S家,/.config/stationlist.xml);
如果(R&GT = sizeof的(文件名)){
    / *需要一个更大的缓存文件名... * /
}否则如果(为r 0){
    / *处理错误... * /
}

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).

解决方案

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

这篇关于函数strncpy并不总是空终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆