I'm taking a intro CS course (CS50x) and came across a slight problem.
Why is this C code producing a segmentation fault when there is only argc[1]?
It should print the statement. Why won't it print the error?
Thanks in advance!
int main(int argc, string argv[])
{
//HOUSEKEEPING
//Get/Validate Key
string key = argv[1];
int finalKey = atoi(key) % 26;
while (argc != 2)
{
for (int i = 0; i < strlen(key); i++)
if (!isdigit(key[i]))
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
//...
argcis an integer argument that keeps track of the number of arguments in the command line, there is noargc[1], there might be anargv[1]if you provide a second command line argument, otherwise trying to read from a non existingargv[x]amounts to undefined behavior, and is the likely culprit of the segmentation fault you are experiencing.In light of that information you'll notice that the
whilestatement makes little sense,argcremains unchanged so the loop will either never execute, or will be infinite ifargcis not2(and the program doesn't crash).The
if-elseis also fishy, it will always print the message and return, if the character is a digit or is not a digit alike.Notwithstanding the goal of the program, a syntactically correct code should look more like this:
* Note that
atoiis quite unsafe, consider usingstrtol. And you can operate directly inargv[1]i.e.int finalKey = atoi(argv[1]) % 26;