Luis Pelaez
Luis Pelaez

Reputation: 17

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 "  );
        }

    }

}

Upvotes: 0

Views: 1116

Answers (2)

rodrigo
rodrigo

Reputation: 98398

There are several issues with this code. First of all you should enable your compiler warnings (and always check them!). If you do, you would see something like this:

warning: implicit declaration of function strcmp

which is a very important warning: it means that you forgot the proper #include and that the compiler will just guess, wrongly in this case.

If you look your favorite C documentation, you'll see that strcmp requires #include <string.h>. If you add that, you'll get a useful message, this time a hard error:

error: too few arguments to function strcmp

And a couple of additional useful warnings:

warning: left-hand operand of comma expression has no effect warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast

With that in mind, take a close inspection of your function call:

if(strcmp((argv[i],"-c") == 0))

There is only an argument to strcmp(), that is the result of this comparison (argv[i],"-c") == 0, where you compare a string "-c" (the left side of the comma operator is ignored) with 0 that is a NULL pointer. You probably want to write:

if (strcmp(argv[i], "-c") == 0)

Upvotes: 2

brokenfoot
brokenfoot

Reputation: 11629

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

Upvotes: 1

Related Questions