这样处理字符串是否安全,请大神看看!!!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* scp_make_file(char *dpath, char *localfile)
{
char *p, *str;
char *dfpath = (char *)malloc(128);
p = (char *)strrchr(localfile, '/');
strcpy(dfpath, dpath);
dfpath = strcat(dfpath, p);
str = dfpath;
free(dfpath);
return str;
}
int main()
{
char *dpath = "/tmp";
char *localfile = "/home/nisp/test.c";
char *p;
p = scp_make_file(dpath, localfile);
printf("%s\n", p);
return 0;
}
[root@gnos-x64-dev ssh2]# gcc -o test test.c
[root@gnos-x64-dev ssh2]# ./test
/tmp/test.c
效果是达到了相要的效果,不知这样处理是不是最理想的,是否有更好的方法,请不吝赐教。。
[解决办法]
1,char *p, *str;要初始化。
2,char *dfpath = (char *)malloc(128);确定能分配成功,假如为null了怎么办?
3,strcpy这个库函数不安全,会溢出,但是使用的时候却不警告,你能保证没有问题了么?
....
[解决办法]
要安全,还要使用_s类型的函数,比如strcat_s,
strcpy_s,
内存分配好要判断是否成功。
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* scp_make_file(char *dpath, char *localfile)
{
char *p;
static char dfpath[_MAX_PATH];
p = (char *)strrchr(localfile, '/');
strncpy(dfpath, dpath,_MAX_PATH-1);dfpath[_MAX_PATH-1]=0;
if (p!=NULL) strncat(dfpath, p,_MAX_PATH-1-strlen(p));
return dfpath;
}
int main()
{
char *dpath = "/tmp";
char *localfile = "/home/nisp/test.c";
char *p;
p = scp_make_file(dpath, localfile);
printf("%s\n", p);
return 0;
}