谁能告诉我为什么这个代码在进入do循环之前会给我一个分段错误11?
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
最佳答案
问题就在网上
strcpy(dirs[counter], token);
首先,将
dirs
中的所有元素初始化为NULL
。因此,在上一行中,您将token
复制到NULL
。