Reputation: 39
I have the below code. I am looking to use command line arguments to gain access to a program or provide an error message. Everything gives the correct error message although at if(argc > 2) I get an error of "Segmentation fault (core dumped)". I cant find the error here. I've done some research and the error is for when I am accessing memory I shouldn't be accessing. Does anyone see in the below code what is causing this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
int a;
if(argc > 2){
printf("Please enter a command");
}
a = atoi(argv[1]);
if(a < 40 || a > 90){
printf("Price must be from 40 to 90 .\n");
}
if(a % 5 != 0){
printf("Price must be a multiple of 5.\n");
}
if(a > 40 || a < 90){
printf("Welcome!\n");
}
}
Upvotes: 1
Views: 387
Reputation: 75062
You did the check, but executed the rest of code unconditionally.
Stop execution when passed argument is not enough.
Also your condition is wrong. The condition should be "less than", not "greater than".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
int a;
if(argc < 2){ /* use correct condition */
printf("Please enter a command");
return 1; /* stop execution */
}
a = atoi(argv[1]);
if(a < 40 || a > 90){
printf("Price must be from 40 to 90 .\n");
}
if(a % 5 != 0){
printf("Price must be a multiple of 5.\n");
}
if(a > 40 || a < 90){
printf("Welcome!\n");
}
}
Upvotes: 2
Reputation: 46
It's probably happening because your code is still proceeding to the next steps after checking for the error conditions. When you have less than 2 arguments, you code will print the error to enter a command, but will continue to the next step of accessing the argv[1] which is invalid (as you don't have a 2nd argument). So you get the segmentation fault here.
Upvotes: 3