复制后为什么我的字符串会被截断?

时间:2015-05-19 14:13:18

标签: c string pointers malloc sizeof

我正在尝试查找是否使用less安装C(不使用系统调用)。但是我复制变量有问题。字符串的内容被截断:

 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

1 个答案:

答案 0 :(得分:6)

我相信,问题就在这里

pathlength = sizeof(pathValue)/sizeof(char);

在这种情况下,pathValue是一个指针,sizeof(pathValue)将只生成指针大小的值,而不是字符串占用的整个内存量

您想要的是使用strlen()代替。

此外,如下面的评论中所述,C标准保证sizeof(char)始终生成1的值。所以,它可以从计算中删除./