Search code examples
csegmentation-faultatoi

Why is atoi giving me a segmentation fault?


I have the following piece of code:

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    int M, N;

    M = 1;
    N = 1;
    curr = 1;

    if ( argv[1][0] == '-' )
    {
        curr = 2;

        char *a = argv[1][1];
        char *b = argv[1][3];

        M = atoi(a);
        N = atoi(b);
    }

    printf("%d\n%d", M, N);
}

So, I pass this program something like this:

a.out -1,2

and instead of getting expected output

1
2

I get a segmentation fault. What gives?


Solution

  • That compiles?!

    char argv*[] is an array of char pointers.

    char *a = argv[1][1] will

    • Get the second char pointer, so now you have a char *.
    • Get the second element in that pointer, which will be a char.

    So now you are assigning a char to a char pointer (which should be a compile error).

    I can only assume you meant to say char *a = &argv[1][1]. Btw, const-correctness would be nice too, so const char *a = &argv[1][1].

    Btw, your code is still very unsafe - you don't even check the size of the string. Imagine what &argv[1][3] does if your string only has two characters.