【问题标题】:Why does ommitting this one line from getopt_long() make a segfault?为什么从 getopt_long() 中省略这一行会导致段错误?
【发布时间】:2016-02-22 08:15:30
【问题描述】:

在我使用gcc -Wall getopt.c -o options 编译并运行一些示例后,乍一看似乎可以正常工作。故意将其绊倒会导致 Segfault 错误。

//straight from the man page
static struct option long_options[] = {
    {"add",     required_argument, 0,  0 },
    {"append",  no_argument,       0,  0 },
    {"delete",  required_argument, 0,  0 },
    {"verbose", no_argument,       0,  0 },
    {"create",  required_argument, 0, 'c'},
    {"file",    required_argument, 0,  0 },
    {0,         0,                 0,  0 } //<-- if i omit this line, it segfaults
};

为什么省略那一行会导致分段错误?

或者更确切地说,以不同的方式询问

为什么我必须将最后一组 struct option array 成员初始化为 null?

【问题讨论】:

  • 您阅读文档了吗?
  • 总是建议在抱怨之前阅读man的功能。
  • 我至少阅读了手册页 20 次。我的眼睛在这一点上是呆滞的。也许只是因为疲倦和睡不好,我认为你们中的任何人都没有真正理解我的问题。手册页从未说明原因。老实说,我不知道为什么。
  • @jargonjunkie 你的why 有一个明显的答案——因为函数需要知道列表的结束位置。最后一条记录作为终止符,它是 C 中的一个常见习惯用法 - 使用 0 或 NULL 终止符来表示列表的结尾,就像字符串一样

标签: c gnu glibc getopt getopt-long


【解决方案1】:

简单。所以处理数组的代码知道它什么时候结束。它被称为哨兵。

【讨论】:

    【解决方案2】:

    来自man

    数组的最后一个元素必须用零填充。

    struct option {
               const char *name;
               int         has_arg;
               int        *flag;
               int         val;
           };
    
     The meanings of the different fields are:
    
      name   is the name of the long option.
    
     has_arg
           is: no_argument (or 0) if the option does not take an
              argument; required_argument (or 1) if the option requires an
              argument; or optional_argument (or 2) if the option takes an
              optional argument.
    
      flag   specifies how results are returned for a long option.  If flag
              is NULL, then getopt_long() returns val.  (For example, the
              calling program may set val to the equivalent short option
              character.)  Otherwise, getopt_long() returns 0, and flag
              points to a variable which is set to val if the option is
              found, but left unchanged if the option is not found.
    
      val    is the value to return, or to load into the variable pointed
              to by flag.
    
      The last element of the array has to be filled with zeros.
    
      If longindex is not NULL, it points to a variable which is set to the
       index of the long option relative to longopts.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多