Reputation: 399
I'm writing a shell in C that's supposed implement several commands, one of them being the change directory command. To change directories, I use chdir(), but every time I run my code, I get a segmentation fault (core dumped) error. Here's my code:
.....
........
char *shell;
while((shell=readline("shell> ") )){
char *cmd = strtok(shell," ");
if(strcmp(cmd,"ls")==0)
{
//do something
}
else if(strcmp(cmd,"print")==0)
{
//do something
}
else if(strcmp(cmd,"cd")==0){
char *directory = strtok(NULL," ");
if(chdir(directory)==-1){
printf("Error\n");
}
else
{
printf("changed directories!");
}
}
add_history(shell);
}
I think I might be using strtok incorrectly?
Any help is appreciated, thank you :)
Upvotes: 0
Views: 880
Reputation: 121397
This
char *directory = strtok(cmd," ");
should be
char *directory = strtok(NULL," ");
When you call strtok()
to get the next token, you pass NULL
to it.
Moreover, strtok()
is not re-entrant. So you can't use it even if your plan was to tokenize a different string. You can use strtok_r()
on POSIX systems.
Upvotes: 1