-1

With the code I have below:

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


int main() {

  int MAX_INPUT_SIZE = 200;
  volatile int running = 1;
  while(running) {

char input[MAX_INPUT_SIZE];
char *tokens[100];
const char* cmds[] = {"wait", "pwd", "cd", "exit"};
char *cmdargs[100];

printf("shell> ");
fgets(input, MAX_INPUT_SIZE, stdin);

//tokenize input string, put each token into an array
char *space;
space = strtok(input, " ");
tokens[0] = space;

int i = 1;
while (space != NULL) {
  space = strtok(NULL, " ");
  tokens[i] = space;
  ++i;
}

//copy tokens after first one into string
strcpy((char*)cmdargs, ("%s ",tokens[1]));
for (i = 2; tokens[i] != NULL; i++) {
  strcat((char*)cmdargs, " ");
  strcat((char*)cmdargs, tokens[i]);
}


//compare tokens[0] to list of internal commands
int isInternal = -1;
for (i = 0; i < 4; i++) {
  if (strcmp(tokens[0], cmds[i]) == 0) {
isInternal = i;
  }
}

char *wd[200];
switch(isInternal) {
case 0:
  //wait
  printf("WAIT \n");
  break;
case 1:
  //pwd
  printf("PWD \n");
  break;
case 2:
  //cd
  printf("CD \n");
  break;
case 3:
  //exit
  printf("EXIT" \n");
  break;
case -1:
  //not internal command, continue
  break;
}


/*
for (i = 0; tokens[i] != NULL; i++) {
  printf("%s ", tokens[i]);
}
printf("\n");
*/
  }
}

gcc gives me an error that says segmentation fault (core dumped) whenever I enter input at all, and I don't understand what's going on. Any ideas?

I fairly certain it has something to do with the switch statement, but I'm not sure where the problem is, since all the switch does is print out a debugging line.

Note: I get the segmentation fault (core dumped) error with inputs: wait, pwd, cd, exit.

IrateIrish
  • 219
  • 2
  • 6
  • 12
  • 5
    `strcpy((char*)cmdargs, ("%s ",tokens[1]));` doesn't do what you think it does. NB - I don't know what you think it does. – Carl Norum Sep 15 '13 at 18:39
  • 2
    What's up with all the typecasting? – Carl Norum Sep 15 '13 at 18:40
  • @CarlNorum: see http://stackoverflow.com/questions/18809734/s-string-not-printing-space-after-string for the intended effect. flexcalibur6, at least go through all your code when you're given help on how to fix it. – Mat Sep 15 '13 at 18:43
  • As no `tokens` element is ever initialized to NULL, the following line could also run amok: `for (i = 2; tokens[i] != NULL; i++)` – Codo Sep 15 '13 at 18:43
  • @CarlNorum You're right, I forgot to change that. – IrateIrish Sep 15 '13 at 18:44

1 Answers1

1

Compile it with the -g tag. Then once you compile it, do "gdb a.out".

Type "run".

Then "where".

It'll tell you what line your seg fault is on.

If you need more help search GDB in google :)

  • Hmm...So it's happening whenever I enter input that is only a single word. If I enter `cd /home` then it doesn't have a problem and runs fine. So my error is when tokens is NULL after tokens[0]. – IrateIrish Sep 15 '13 at 18:52