【发布时间】:2017-03-05 21:57:40
【问题描述】:
我正在使用 c 创建自己的 shell,但我不断收到错误消息,我认为这涉及到使用 strtok 和 strcat。请注意,path 和 userInput 是全局字符串。
int myFunction()
{
char *possiblePaths = getenv(PATH);
path = strtok(possiblePaths,":");
path = strcat(path,"/");
path = strcat(path, userInput);
while(path != NULL)
{
//other code
path = strtok(NULL,":");
path = strcat(path,"/");
path = strcat(path, userInput);
}
return 1;
}
getenv 给了我一个字符串,
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/texbin
然后我想做的是基于':' 标记字符串,然后连接'/' 加上我的全局变量userInput。输出应该是这样的,
/opt/local/bin/userInput
然后下一次我会得到循环
/opt/local/sbin/userInput
不幸的是,我得到了以下信息
/opt/local/bin/userInput
userInput/userInput
/userInput/userInput
/userInput/userInput
我的第一个 strtok 和 strcat 给了我正确的结果。但随后/userInput 将继续循环,直到我遇到分段错误。我很确定我的错误与使用 strtok 和 strcat 混合指针有关,但我不知道如何解决它。
【问题讨论】:
-
“注意 path 和 userInput 是全局字符串” - 不要要求我们注意任何事情。将他们的定义明确地放在你的minimal reproducible example中。
-
你不应该破解
getenv()返回的字符串——你正在修改你的shell的PATH环境。如果你小心的话,这可能无关紧要(但它可能确实如此——你必须使用execve()或类似的,并明确设置一个安全的 PATH 值),但你可能需要复制并使用那个。 -
另外,当您使用
strcat()时,您将使用您连接的内容覆盖 PATH 的下一段。你需要重新考虑你在做什么——弄清楚你的字符串操作在哪里读写。此刻,你一团糟。 -
您的
strcat调用会用下一个strtok覆盖您计划读取的空间。 -
您似乎混淆了“字符串”和“指针”,这是 C 中两个非常不同(尽管相关)的概念。您需要返回并重新阅读 C 文本介绍。
标签: c string pointers strtok strcat