【发布时间】:2013-02-17 13:29:15
【问题描述】:
#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) 循环将退出。但这部分将单独完成。 现在有人可以帮我处理这个代码示例吗?
谢谢!
【问题讨论】:
-
显然您正在访问超出数组的范围。做一些调试来检查索引的值。
-
一个提示:您不要终止
temp字符串。或arg字符串。 -
其实我是用gdb来隔离线路的。但是您还没有回答这个问题 - 它如何接受一条线,然后继续在完全相同的线(逻辑上相似)处给出分段错误?
-
@Karthik 在下面查看我的答案
-
这是一个非常糟糕的做法。您应该始终添加空终止字符!
标签: c shell segmentation-fault