gpt4 book ai didi

c - 空白行段。错误(自己写shell)

转载 作者:行者123 更新时间:2023-11-30 20:24:23 24 4
gpt4 key购买 nike

我仍在学习编写简单的 shell。

我希望这个 shell 允许空行和注释。

我做了一些编码,遇到了一个问题,如果我直接输入回车(空行),它会直接seg.fault core dumped。

我不知道到底哪里出了问题,因为我打印了所有内容,看起来一切都很好。我在这行中唯一怀疑的是

if (args[0] == NULL || !(strncmp(args[0],"#",1))) {
exitstat = 0;
}

我从基本分割命令函数中获取了参数。奇怪的是评论效果很好。

下面是我的函数,用于读取用户输入并拆分它们(如果我没有记错的话,则进行标记)。它们非常基础,因为我是从互联网教程中学习这些功能的。

char *commandInput() {
char *command = NULL;
ssize_t bufsize = 0;
getline(&command, &bufsize, stdin);
return command;
}

char **splitLine(char *command) {
int bufsize = 64,
int position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token;

token = strtok(command, DELIMITER);
while (token != NULL) {
tokens[position] = token;
position++;

if (position >= bufsize) {
bufsize += 64;
tokens = realloc(tokens, bufsize * sizeof(char*));
}
token = strtok(NULL, DELIMITER);
}
tokens[position] = NULL;
return tokens;
}

如果我输入空行,任何人都可以帮助我识别导致 seg.fault 的原因吗?谢谢。

编辑

我使用了调试器(经过多次尝试终于成功使用它),结果发现错误位于我没想到会引起任何问题的行(参见 ---UPDATE----)。

我处理 commandInput 函数的方式是在 main() 函数中,我写的

int main () {
......
char * command = NULL
char **args;
command = commandInput();
args= splitLine(command);

------------------ UPDATE!(CAUSING ERROR IF STATEMENT) ---------------
background = 0
numbarguments = 0

// Condition to check whether there is a start program running in backgrond
if (!(strncmp(args[numbarguments - 1], "&",1))) {
background = 1;
args[numbarguments - 1] = NULL;
}

----------------------------------------------

if (args[0] == NULL || !(strncmp(args[0],"#",1))) {
exitstat = 0;
}
....... //(comparing the arguments other than null)
}

因此,有关导致我出现 seg.fault 的条件的任何建议。谢谢。

最佳答案

您传递给 splitline 的参数已被修改。 strtok 具有通过插入\0 并返回指向子字符串的指针来修改它获得的字符串的效果。 strtok返回的并不是你可以直接存储以供以后使用的东西,而是你需要复制它。

 token = strtok(command, DELIMITER); 
while (token != NULL)
{
tokens[position] = malloc(strlen(token)+1);
strcpy(tokesn[position],token);
...

换句话说,将指针数组分配给字符串是不够的,您还需要分配空间来保存用 strtok 标记的字符串。

<小时/>

代码

if (!(strncmp(args[numbarguments - 1], "&",1))) {
background = 1;
args[numbarguments - 1] = NULL;
}

看起来不对,numberarguments 最初为 0,因此您将 args[-1]"&" 进行比较,然后分配 args[-1] = NULL 这可能会导致段错误。

关于c - 空白行段。错误(自己写shell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33687204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com