if statement - Segmentation Fault (Core Dumped) - C Arguments -
every time run program below in following way: ./a.out -a -b
runs properly. if choose run ./a.out -a
, result in segmentation fault (core dumped). there way can fix this?
int main(int argc, char *argv[]) { if (argc > 1) { if (strcmp(argv[1],"-a") == 0) {... if (strcmp(argv[2],"-b") == 0) {...} } } }
when run ./a.out -a
, 1 argument, should not check strcmp(argv[2],"-b")
, because there no third argument, , reading argv[2]
result in undefined behavior.
you can fix adding check before doing strcmp(argv[2],"-b")
.
int main(int argc, char *argv[]) { if (argc > 1) { if (strcmp(argv[1],"-a") == 0) {... if (argc > 2 && strcmp(argv[2],"-b") == 0) {...} } } }
this looks pretty ugly work.
Comments
Post a Comment