【问题标题】:Why is my string truncated when copied?为什么我的字符串在复制时被截断?
【发布时间】: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

【问题讨论】:

标签: c string pointers malloc sizeof


【解决方案1】:

我相信,问题就在这里

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

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

你想要在这里使用strlen()。

另外,正如下面评论中提到的,C 标准保证sizeof(char) 将始终产生1 的值。所以,它可以从计算中删除。/

【讨论】:

  • 而且sizeof(char) != 1是不可能的。
  • @moffeltje 我设法更快地发现了错误。通常,这是一个常见的。 :-)
  • 你说produce很好,因为sizeof()不return,既然是运营商,我只是回答了一个问题,错了说returned,我就这样离开了,因为我没有想到合适的词。
  • @iharob 不知何故我在第一次出现时也做了同样的事情,现在更正了。 :-)
猜你喜欢
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 2018-10-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
相关资源
最近更新 更多