Search code examples
csegmentation-faultcoredumpstrcmp

Segmentation fault (core dumped) error with strcmp


The file is called "options". Whenever I run this code in the console, here I have some possibilities:

./options -c
./options -c -E

I get the message:"Segmentation fault (core dumped)" Dont really know what to do, I might need some help please.

#include <stdio.h>

int main(int argc, char *argv[]){    
    int i;
    for(i = 0; i < argc; i++){
        if(strcmp((argv[i],"-c") == 0)){
            printf("Argumento %d es %s\n", i, "Compilar");
        }
        else if(strcmp((argv[i],"-E") == 0)){
            printf("Argumento %d es %s\n", i, "Preprocesar");
        }  
        else if(strcmp((argv[i],"-i") == 0)){
            printf("Argumento %d es %s\n", i, "Incluir "  );
        }

    }

}

Solution

  • There are several changes you need to make to your code:
    1. add string.h header
    2. re-write strcmp lines: right now it is - strcmp((argv[i],"-c") == 0)

    With above changes:

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[]){
        int i;
        for(i = 0; i < argc; i++){
            if(strcmp(argv[i],"-c") == 0){
                printf("Argumento %d es %s\n", i, "Compilar");
            }
            else if(strcmp(argv[i],"-E") == 0){
                printf("Argumento %d es %s\n", i, "Preprocesar");
            }
            else if(strcmp(argv[i],"-i") == 0){
                printf("Argumento %d es %s\n", i, "Incluir "  );
            }
    
        }
    
    }
    

    Output:

    $ ./a.out -E
    Argumento 1 es Preprocesar