【发布时间】:2015-07-31 10:19:23
【问题描述】:
我正在尝试查找是否使用C 安装了less(不使用系统调用)。但是我复制变量有问题。字符串内容被截断:
int ret;
char * pathValue;
char * pathValue2;
char *token3;
char * new_str ;
int pathlength;
pathValue = getenv ("PATH");
if (! pathValue) {
printf ("'%s' is not set.\n", "PATH");
}
else {
printf ("'%s' is set to %s.\n", "PATH", pathValue);
}
pathlength = sizeof(pathValue)/sizeof(char);
pathValue2 = malloc(sizeof(pathValue));
strncpy(pathValue2, pathValue, pathlength);
printf ("pathValue2 is to %s.\n", pathValue2);
token3 = strtok(pathValue2, ":");
ret = 1;
printf("Looking for less\n");
while( token3 != NULL ) {
printf("Looking for less %s\n", token3);
if((new_str = malloc(strlen(token3)+strlen("/less")+1)) != NULL) {
new_str[0] = '\0';
strcat(new_str,token3);
strcat(new_str,"/less");
printf( " %s\n", new_str );
if (file_exist (new_str)) {
printf("Found less\n");
ret=0;
}
free(new_str);
} else {
printf("malloc failed!\n");
}
token3 = strtok(NULL, ":");
}
free(pathValue2);
如果我运行程序,第一个变量是我正确的PATH,但是当我复制它时,它已被截断。这里有什么问题?
$ ./a.out 'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games. pathValue2 is to /usr/loc. Looking for less Looking for less /usr/loc /usr/loc/less
【问题讨论】:
-
我建议您阅读以下内容:What do I do when someone answers my question?
标签: c string pointers malloc sizeof