Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

c - 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 != '')
{
    printf("Usage: ./caesar key
");
    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 != ''), 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 != '')

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...