Search code examples
cshellcoredump

Minishell 'segmentation fault, core dumped' error in C


Following is a part of my code for my shell. The code works, but when I try to enter a command like "ls", my program crashes. I think that's a right error because I try to access to the "/bin" file.


void lecture (char cmd1[], char *argv[]){ 
    int x = 0;
    char ligne [1024];
    char *aux [100], *pch;
    while (1){
        int mot = fgetc (stdin);
        ligne[x] = (char) mot;
        x++;
        if (mot == (int)'\n') break;
    }    
    aux[0] = strtok (ligne, " \n");
    strcpy(cmd1,aux[0]); 
    for (int i = 1; i <= 1024; i++){
        argv[i+1] = aux[i];
    }
}

int main(){
    char cmd1 [100];
    char cmd2 [100];
    int a = 10;
    char *argv [20];
    char *envp[] = {(char *) "PATH=/bin", 0};
    while (1){
        affichage();
        lecture (cmd2, argv); 
        printf("Test");
        if ( fork() != 0){
            printf("Err");
            wait (NULL);
        }else{
            strcpy(cmd1, "/bin/");
            strcat(cmd1, cmd2);
            execve(cmd1, argv, envp);
        }
    }    
}


Solution

  • I get something working without SIGSEGV with following modification in lecture:

    for (int i = 0; i < 20; i++){
    

    Example:

     ./ms
    ls
    ����: cannot access 'ls': No such file or directory
    TestErr
    ...
    

    But you can also debug this as I did with compiling in debug mode:

    gcc -o ms -g -Wall -pedantic -Wextra -std=c11 ms.c
    

    and using gdb to check where SIGSEGV occurs.

    Note that you are expected to post a https://stackoverflow.com/help/minimal-reproducible-example with full code (here we are missing affichage) and

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>