-3

I want to make a program that imitates the use of cd in UNIX. Obviously the best option is chdir. However when the user types cd /home I get Segmentation fault. When I use gdb, it prints:

Program received signal SIGSEGV, Segmentation fault. __rawmemchr_avx2 () at ../sysdeps/x86_64/multiarch/memchr-avx2.S:61
61  ../sysdeps/x86_64/multiarch/memchr-avx2.S: The file of directory does not exist.

The code looks like this:

void cd(char buff[]){
     if(chdir(buff)==-1){
          printf("Problem with directory\n");
     }
}

int main(int argc, char *argv[]){
    char* token;
    char buffer[256];

    printf("Welcome user\n");
    sscanf("%s",buffer);
    token=strtok(buff," ");
    if(strcmp(token,"cd")==0||strcmp(token,"cd\n")==0){
        cd(strtok(NULL," ");
    }

    return 0;
}

Than you for your time.

Azzarian
  • 153
  • 2
  • 13

2 Answers2

0

You have made a few syntactic and logical mistakes inside the provided code, like for example buff instead of buffer in main()and sscanf instead of scanf for giving the input string.

Also, you wrote cd(strtok(NULL," "); but a closing brace is missing for this statement to compile: cd(strtok(NULL," "));.

I've corrected the code and the output file runs fine on my platform - with GCC on Ubuntu GNU/Linux.

Here is the corrected code:

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

void cd(char buff[]){
     if(chdir(buff)==-1){
          printf("Problem with directory\n");
     }
}

int main(int argc, char *argv[]){
    char* token;
    char buffer[256];

    printf("Welcome user\n");
    scanf("%s",buffer);
    token=strtok(buffer," ");
    if(strcmp(token,"cd")==0||strcmp(token,"cd\n")==0){
        cd(strtok(NULL," "));
    }

    return 0;
}

Try it with this.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
0

This code has several problems:

1) even if sscanf is swapped for scanf, it does not do what you probably expect it to (read the whole line inserted by the user). scanf with %s will read up to the first whitespace. So, your buffer will actually contain cd\0 instead of cd /home\0 like you expect it to. Use fgets instead.

2) You must check that strtok does not return a NULL pointer. This is what is currently causing your segfault.

Something like this:

void cd(char buff[]) {
     if(chdir(buff) == -1) {
          printf("Problem with directory\n");
     }
}

int main(int argc, char *argv[]){
    char* token;
    char buffer[256];

    printf("Welcome user\n");
    // reads the whole line into buffer
    fgets(buffer, 256, stdin);
    token = strtok(buffer, " ");

    if (strcmp(token, "cd") == 0){
        token = strtok(NULL," ");
        // we must check if there are any tokens left
        if (token != NULL) {
            // we must remove the trailing newline character that is included by fgets
            cd(strtok(token, "\n"));
        }
    }

    return 0;
}
Uku Loskit
  • 40,868
  • 9
  • 92
  • 93