为什么这段代码在进入do循环之前给了我一个段错误?

时间:2014-02-05 01:27:43

标签: c

任何人都可以告诉我为什么这段代码在进入do循环之前给我一个分段错误?

int parsePath(char *dirs[]){
    char *pathEnvVar;
    char *thePath;

    for(int i=0; i<MAX_ARGS; i++)
        dirs[i]=NULL;

    pathEnvVar = (char *) getenv("PATH");
    thePath = (char *) malloc(strlen(pathEnvVar) +1);
    strcpy(thePath, pathEnvVar);
    printf("the path is %s \n", thePath );
    /* Loop to parse thePath.  Look for a ':' delimiter between each path name */       
    const char delim[2] = ":";
    char *token;
    int counter = 0;
    /* get the first token */
    token = strtok(thePath, delim);
   printf("got to line 80 \n");
   printf("token is %s \n", token);
   printf("token is %u \n", (int)token);
   printf("got to line 83 \n");
   /* walk through other tokens */
   do 
   {
        printf("help me");
      counter++;
      strcpy(dirs[counter], token);
      printf("Path is %s", dirs[counter]);    

   }while((token = strtok(NULL, delim)));
   return 0;    
}

我很困惑,因为它打印“到第83行”而不是“帮帮我”所以由于某种原因它不会进入do循环?

这是输出:

the path is /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/texbin 
got to line 80 
token is /usr/bin 
token is 2302687600 
got to line 83 
Segmentation fault: 11

1 个答案:

答案 0 :(得分:1)

问题在于

strcpy(dirs[counter], token);

首先,您将dirs中的所有元素初始化为NULL。因此,在上面的行中,您将token复制到NULL