#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;
}
}
}
}
Hi, The above is a sample of code from my custom shell's code. I haven't completed the code yet, just in case you're wondering about the program going on till infinity. Now, I am getting a segmentation fault at a line (its been commented), but I don't understand why. I perform the same check as Line 42 at Line 38, but it didn't give a segmentation fault there. Can anyone help me out?
The purpose of some of the mentioned variables is as follows: "temp" is a pointer to a memory location that holds the entire command given to the shell. "args" is an array of pointers, each pointer pointing to a memory location that contains the individual arguments in the command.
For example, "temp" will hold the string - gcc hello.c -o hello, if that has been passed to my shell. And args[0] will point to "gcc", args[1] will point to "hello.c" and so on.
That is the purpose of this sample of code. It will store all the arguments in "args" after eliminating the white spaces from "temp". The while(1) loop will exit when the person calls the exit command from the shell. But that part of it will be done separately. Now can anyone help me with this sample of code?
Thanks!