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?
Because here
flagis set toNULL, then hereflags's value (NULL) is passed tostrtol(), which does not changeflags's value in any way, it isNULLbefore and after the call tostrtol().and finally here
flag, which has the valueNULL, is dereferenced, which invokes undefined behaviour, which could lead to anything, which in your case is a crash.