分段错误 - 使用getopt时出现Core Dumped错误

use*_*433 1 c c++ unix gcc ansi

我知道这个问题被多次询问,但我仍然无法弄清楚这一点

#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);
}   
Run Code Online (Sandbox Code Playgroud)

我正在使用以下命令执行我的程序

./a.out -d -h -l -t 55
Run Code Online (Sandbox Code Playgroud)

我收到核心转储错误.我在谷歌上看了几个例子,但我仍然面临着这个问题.有人可以帮忙吗?

Cha*_*rns 8

您需要阅读getopt()的手册页

  while ((ch = getopt(argc, argv, "dhlprtns")) != -1)
                                   ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

这与您使用参数的方式不对应.你希望冒号":"在期望参数的标志之后.在您的代码中,"d"后面没有冒号,但您似乎想要一个值:

  case 'd':
    debug_flag=atoi(optarg);        /* print address in output */
    break;
Run Code Online (Sandbox Code Playgroud)

所以正在发生的事情是你在呼唤atoi(0),这就是断层错误.

这是手册页中的示例,注意"b"后面没有冒号的"b".

#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;
Run Code Online (Sandbox Code Playgroud)