我正在编写一个函数来获取系统的路径环境变量,分割每个路径,然后在其他一些额外的字符上连接到每个路径的末尾.
一切正常,直到我使用该strcat()功能(见下面的代码).
char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = (char *)malloc(strlen(path) + 1);
char* token[80];
int j, i=0; // used to iterate through array
strcpy(pathDeepCopy, path);
//parse and split
token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0
//place in array
while(token[i]!= NULL) { //ensure a pointer was found
i++;
token[i] = strtok(NULL, ":"); //continue to tokenize the string
}
for(j = 0; j <= i-1; j++) {
strcat(token[j], "/");
//strcat(token[j], exeName);
printf("%s\n", token[j]); //print out all of the tokens
}
}
Run Code Online (Sandbox Code Playgroud)
我的shell输出是这样的(我将"/ which"连接到所有内容上):
...
/usr/local/applic/Maple/bin/which
which/which
/usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which
which/which
Bus error (core dumped)
Run Code Online (Sandbox Code Playgroud)
我想知道为什么strcat要显示一个新行然后重复which/which.我也想知道Bus error (core dumped)最后的情况.
有没有人在使用之前看过这个strcat()?如果是这样,任何人都知道如何解决它?
谢谢
strtok()没有给你一个新的字符串.
它通过在分割字符所在的位置插入char'\ 0'来破坏输入字符串.
所以你使用strcat(token [j],"/")会将'/'字符放在'\ 0'所在的位置.
此外,最后一个标记将开始将已分配内存末尾的"哪个"附加到未知内存中.
您可以使用strtok()将字符串拆分为块.但是如果你想在令牌上附加任何东西,你需要制作令牌的副本,否则你的追加将溢出到下一个令牌上.
你需要更加小心你的内存分配,你在整个地方泄漏内存:-)
PS.如果必须使用C-Strings.使用strdup()复制字符串.
char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = strdup(path);
char* token[80];
int j, i; // used to iterate through array
token[0] = strtok(pathDeepCopy, ":");
for(i = 0;(token[i] != NULL) && (i < 80);++i)
{
token[i] = strtok(NULL, ":");
}
for(j = 0; j <= i; ++j)
{
char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1);
strcpy(tmp,token[j]);
strcat(tmp,"/");
strcat(tmp,exeName);
printf("%s\n",tmp); //print out all of the tokens
free(tmp);
}
free(pathDeepCopy);
}
Run Code Online (Sandbox Code Playgroud)