我正在编写一个程序,它需要在分隔符“:”处解析 PATH 环境变量。一切似乎都在正常工作,直到函数 Chop 尝试返回数组。然后我收到以下错误:“glibc检测到./a.out:损坏的双链表:0x08f8f148”。我使用chop也解析用户输入并且它工作正常。任何帮助是极大的赞赏。
//Parse environment variable
char const* pPath = getenv("PATH");
if (pPath == NULL){;}
else{
string ePath(pPath);
envp = chop(ePath,':');
}
char **chop(string s, char c){
int i, j, k, len, words = 0;
len = s.length();
//determine # of words
for(i=0;i<len+1;i++){
if(s[i] == c || s[i] == '\0'){words++;}
}
char **array;
string x;
//allocate memory for char pointers
if((array=(char**)malloc((words+1)*sizeof(char*))) == NULL){return NULL;}
array[0] = &x[0];
i = 0; k = 0;
//split string on char c
for(j = 1; j < (words+1); j++,k++,i++){
//read in characters until delimiter
while (s[k] != c && s[k] != '\0'){
x[i] = s[k];
i++; k++;
}
x[i] = '\0';
array[j] = &x[i+1];
}
array[j] = 0;
return array;
}