Segmentation fault - Core Dumped error while using getopt Segmentation fault - Core Dumped error while using getopt unix unix

Segmentation fault - Core Dumped error while using getopt


You need to read the man page for getopt()

  while ((ch = getopt(argc, argv, "dhlprtns")) != -1)                                   ^^^^^^^^

This does not correspond to the way you are using the arguments. You want colons ":" after the flags which expect arguments. In your code"d" is not followed by a colon and yet you seem to want an value for it:

  case 'd':    debug_flag=atoi(optarg);        /* print address in output */    break;

So what is happening is you are calling atoi(0) and this is seg faulting.

Here's the example from the man page, note how "b" is not followed by acolon while "f" is.

#include <unistd.h> int bflag, ch, fd; bflag = 0; while ((ch = getopt(argc, argv, "bf:")) != -1) {         switch (ch) {         case 'b':                 bflag = 1;                 break;         case 'f':                 if ((fd = open(optarg, O_RDONLY, 0)) < 0) {                         (void)fprintf(stderr,                             "myname: %s: %s\n", optarg, strerror(errno));                         exit(1);                 }                 break;         case '?':         default:                 usage();         } } argc -= optind; argv += optind;


This may be of use to others: You will also get a segfault if you specify an option letter as both without colon, and with colon eg "dabcd:e" - in this case "d" occurs with and without colon.... and then use that option letter.

It appears getopt and its variants do not check for this conflict and return an error!