I have this code that needs to take in 3 command line arguments that are numbers in order to convert from Fahrenheit to Celsius. I have everything working in the program but I am having issues with changing the 'step' variable to int 1 if it is not specified as an argument when running the program. I added the if statement to check if the argument exists and then have that change the value to one if it does not but it returns a segmentation fault. Here is the if statement:
int step = atoi(argv[3]);
if(argc == 2){
step = 1;
return step;
}
Here are the results of running the program:
root@computer:/home/sus/cyb126/homework$./temperature_chart 32 212
Segmentation fault (core dumped)
root@computer:/home/sus/cyb126/homework$./temperature_chart 32 212 20
32 0.000000
52 11.111111
72 22.222221
92 33.333332
112 44.444443
132 55.555557
152 66.666664
172 77.777779
192 88.888885
212 100.000000
I don't understand why it returns a segmentation fault by compiles fine with no warnings. I can only think that it does not listen to the if statement for some reason.
Appreciate any help.
Changed code to the following after I was answered with good advice below:
int step;
if (argc == 2) {
step = atoi(argv[3]);
}
else {
step = 1;
}
CodePudding user response:
When you pass 2 arguments the argv array is only 3 elements long ( the number of elements is always argc 1). This means that by accessing argv[3]
you are accessing the fourth element of a three element vector. This is an out of bound access and you get a seg fault.