getting segmentation fault | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

getting segmentation fault

Hello everyone, I wrote a caesar cipher program in c. when you run the code the user is suppose to add a second argument; the cipher key. Ex: ./caesar 1. The code runs properly, however, if the user does not add that second argument, the code outputs a segmentation fault. Does anyone know why this is happening? Any help is appreciated. Thank you. The code can be found in this link. Also, I'm using the cs50 library, so it won't run on Sololearn. https://code.sololearn.com/c4A14a12a15A

7th Apr 2021, 11:57 PM
David
David - avatar
4 Answers
+ 2
On line 9, you are checking if `argc != 2` which will only be true when argc is not 2 which means more than 1 or no argument was passed. But then on line 14, you are accessing argv[1] anyway. Which means even if the user pass 0 arguments, the if condition will print "Usage: ./caesar key" And then will proceed to execute line 14, where you are accessing the 1st index of argv, which doesn't exist. This will be a segmentation fault. If the if-condition is true on line 14, you most probably want to exit the code. So adding the line `exit(EXIT_FAILURE);` After line 15 will fix the problem.
8th Apr 2021, 3:31 AM
XXX
XXX - avatar
+ 2
the main argument takes its 2 paramaters: int argc and char *argv[]. the first line in the main program is to check if a second argument was given. on line 9 where it says: if (argc != 2) ... that is basically saying if there isnt 1 argument given (the program name counts as the first) than it prints its correct usage. since its coded to only take arguments before startup, thats the only way it will run
8th Apr 2021, 12:27 AM
Slick
Slick - avatar
+ 2
Also, is `false` even valid? I found from the cs50 documentation that `string` is there in the cs50.h header file, but I didn't find `false`.
8th Apr 2021, 3:38 AM
XXX
XXX - avatar
0
XXX thanks for your help. That makes sense.
8th Apr 2021, 6:59 PM
David
David - avatar