Search code examples
c++cunixgccansi-c

Segmentation fault - Core Dumped error while using getopt


I know this queston has been asked multiple times, but still I am unable to figure this out

#include<stdio.h>
#include<getopt.h>
int ch;
int queue_time=60;
int thread_num=4;
char *scheduling_algo="FCFS";
extern char *optarg;
int port=8080;
int debug_flag,h_flag,l_flag;
int main(int argc,char *argv[])
{
  while ((ch = getopt(argc, argv, "dhlprtns")) != -1)
switch(ch)
{
  case 'd':
    debug_flag=atoi(optarg);        /* print address in output */
    break;
  case 'h':
    h_flag=atoi(optarg);
    break;
  case 'l':
    l_flag=atoi(optarg);; 
    break;
  case 'p':
    port = atoi(optarg);
    break;
case 'r':
    printf("%s",optarg); 
    break;
case 't':
    queue_time = atoi(optarg);
    break;
case 'n':
    thread_num = atoi(optarg);
    break;
case 's':
    scheduling_algo = optarg;
    break;
default:
    printf("nothing was passed");
}

    printf("%d",queue_time);
    printf("%d",debug_flag);
    printf("%d",h_flag);
    printf("%d",l_flag);
}   

I am executing my program using the following command

./a.out -d -h -l -t 55

I am getting the core dumped error . I read a few examples on google, but still I am facing this problem. Can anyone please help?


Solution

  • 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 a colon 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;