cpointerssegmentation-faultstrtol

Why is the second argument not working with strtol?


I did this something like this:

/* convert the argv[1] into Integer and store the result in key
 * using library function: strtol() to do it */
char **flag = NULL;
key = strtol(argv[1], flag, 10);

// if argv[1] is not all digits
if (**flag != '\0')
{
    printf("Usage: ./caesar key\n");
    return 1;
}

But it throws a segmentation fault. I am not sure why.

In the C documentation, strtol is prototyped as long int strtol(const char *nptr, char **endptr, int base). Why am I getting a segmentation fault?

And when change some parts of the code to char *flag, strtol(argv[1], &flag, 10), and if (*flag != '\0'), everything works as expected.

I understand (sort of) how making the edits corrects the code. However, I do not know why the original code does not work. Does anyone have a clue?


Solution

  • I do not know why the original code does not work? Does anyone have any clue?

    Because here

    char **flag = NULL;
    

    flag is set to NULL, then here

    key = strtol(argv[1], flag, 10);
    

    flags's value (NULL) is passed to strtol(), which does not change flags's value in any way, it is NULL before and after the call to strtol().

    and finally here

    if (**flag != '\0')
    

    flag, which has the value NULL, is dereferenced, which invokes undefined behaviour, which could lead to anything, which in your case is a crash.