gpt4 book ai didi

c - 段错误 - 自定义 Shell

转载 作者:行者123 更新时间:2023-11-30 15:51:21 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define BUF 1024 //I assume that the maximum number of arguments is 1024

main()
{
char c;
char *temp;
char *arg[BUF]; //the commands
int i=1,j,k,iter=0;

while(1)
{
i=1;
iter=0;
printf("CS21> ");
temp = malloc(sizeof(char));
while((c=fgetc(stdin))!='\n')
{
temp = realloc(temp, i*sizeof(char));

temp[i-1]=c;
i++;
}

j=0;
while(j<strlen(temp))
{
if(temp[j]==' ')
{
j++;
continue;
}

if(temp[j]!=' ') //Line 38: Same check performed as Line 42
{
k=j;
arg[iter] = malloc(sizeof(char));
while(temp[k]!=' ') //Line 42: Segmentation Fault here
{
arg[iter] = realloc(arg[iter],(k-j+1)*sizeof(char));
arg[iter][k-j]=temp[k];
k++;
}
iter++;
k++;
j=k;
continue;
}
}
}
}

嗨,以上是我的自定义 shell 代码中的代码示例。我还没有完成代码,以防万一您想知道程序会一直持续到无穷大。现在,我在一行中遇到段错误(已注释),但我不明白为什么。我在第 38 行执行了与第 42 行相同的检查,但它没有给出段错误。谁能帮帮我吗?

上述一些变量的用途如下:“temp”是一个指向内存位置的指针,该位置保存了给 shell 的整个命令。“args”是一个指针数组,每个指针都指向包含命令中各个参数的内存位置。

例如,“temp”将保存字符串 - gcc hello.c -o hello(如果该字符串已传递到我的 shell)。并且args[0]将指向“gcc”,args[1]将指向“hello.c”等等。

这就是此代码示例的目的。在消除“temp”中的空格后,它将把所有参数存储在“args”中。当用户从 shell 调用 exit 命令时, while(1) 循环将退出。但这部分将单独完成。现在有人可以帮我处理这个代码示例吗?

谢谢!

最佳答案

当字符串中没有空格时(最后一个参数的情况), while(temp[k]!=' ') 中的循环不会完成。如果 k > strlen(temp),则需要停止循环。

只是我的评论:到底谁在教按字节读取并在每个字符后重新分配?这太尴尬了...

关于c - 段错误 - 自定义 Shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184970/

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