strtok没有正确拆分字符串

时间:2015-10-29 10:06:49

标签: c string strtok

当我将“/ usr / bin:/ bin:/ usr / sbin:/ sbin:/ usr / local / bin”传递给我的函数时,当我打印每个令牌时,我只获得3个输出(而不是5个) 。检查100次后我没有看到任何问题。但每次只打印3个输出。

的/ usr / bin中

/ bin中

/ U / USR / bin中

(空)

char** tokenised(char* directories) {
    char** directoryArray = malloc(1000*sizeof(char*));
    char *token;
    int i = 0;

     //First token
     token = strtok(directories, ":");

     while(token != NULL) 
     {
         directoryArray[i] = strdup(token);
         token = strtok(NULL, ":");
         i++;
     }

     int j = 0; 
     while(directoryArray[j] != NULL) {
          printf("%s\n", directoryArray[j]);
          j++;
     }
     return directoryArray;
}

调用tokenised的函数,它有问题

  int searchForFile(int argc, char *argv[]) {
     char* fileName = argv[0];
     char* pathBuffer = malloc(sizeof(PATH)+1);
     strcpy(pathBuffer, PATH);

     int i = 0;
     printf("%s\n", PATH);

     char** directoryArray = tokenised(pathBuffer);
     printf("%s\n", directoryArray[4]);

     while(directoryArray[i] != NULL) {
         printf("%i\n", i);
         printf("Searching directory: '%s'\n", directoryArray[i]);
         //Form an address out 2 strings
              char *address =   malloc(sizeof(char)*strlen(directoryArray[i])+sizeof(char)*strlen(fileName)+1*sizeof(char));
          strcpy(address, directoryArray[i]);
          strcat(address, "/");
          strcat(address, fileName);
          argv[0] = address;
          if(execute(argc, argv) == 0) {
              return 0;
          }
    i++;
  }
  printf("Search for file: '%s' failed.", fileName);
  return 1;
  } 

2 个答案:

答案 0 :(得分:1)

问题在于您pathBuffer的制作方式。根据您的评论,PATH是一个指针。因此,通话

char* pathBuffer = malloc(sizeof(PATH)+1);
strcpy(pathBuffer, PATH);

为指针加上一个字节分配内存,而不是为PATH指针的内容分配内存。将长输入字符串复制到此短缓冲区会导致未定义的行为。最有可能的是,字符串尾部的内存与其他一些数据结构共享,导致在strtok开始处理字符串之前截断字符串。您可以通过在directories函数的开头打印tokenised()字符串来确认这一点。

由于您在其他地方使用strdup,因此请将上述行更改为

char* pathBuffer = strdup(PATH);

将解决问题。

答案 1 :(得分:0)

此循环后

 while(token != NULL) 
 {
     directoryArray[i] = strdup(token);
     token = strtok(NULL, ":");
     i++;
 }

directoryArray[i] = NULL;

directoryArray[i] = token;

在这种情况下,以下循环将是正确的

 int j = 0; 
 while(directoryArray[j] != NULL) {
      printf("%s\n", directoryArray[j]);
      j++;
 }

修改:在添加代码示例后,再添加此语句

char *address =   malloc(sizeof(char)*strlen(directoryArray[i])+sizeof(char)*strlen(fileName)+1*sizeof(char));

必须更改为

char *address =   malloc( strlen(directoryArray[i])+strlen(fileName)+2);
                                                                     ^^^

因为你还在字符串

附加一个斜杠
strcat(address, "/");