【问题标题】:Why does popt segfault when a string is too short?为什么当字符串太短时会弹出段错误?
【发布时间】:2015-04-23 05:49:34
【问题描述】:

argDescrip 字符串不够长时,为什么popt 会出现段错误?

举个例子:

#include <popt.h>

struct poptOption options[] = {
  POPT_AUTOHELP
  {
    .longName = "color",
    .shortName = '\0',
    .argInfo = POPT_ARG_STRING
               | POPT_ARGFLAG_OPTIONAL
               | POPT_ARGFLAG_SHOW_DEFAULT,
    .arg = (void*) "auto",
    .val = 1,
    .descrip = "Whether or not to use colored output",
    .argDescrip = "always|never|auto (checks if TTY)"
  },
  POPT_TABLEEND
};


int main(int argc, const char** argv) {
  // get popt context
  poptContext ctx = poptGetContext(
      "program",
      argc, argv,
      options,
      POPT_CONTEXT_POSIXMEHARDER);

  // parse
  poptGetNextOpt(ctx);

  return 0;
}

以上段错误:

/tmp$ ./a.out --help
Usage: a.out [OPTION...]
[1]    47468 segmentation fault  ./a.out --help

虽然将.argDescrip 改为

.argDescrip = "always|never|auto (checks if TTY) "
              "........................................."

popt 欣然接受它并显示输出:

/tmp$ ./a.out --help
Usage: a.out [OPTION...]
      --color[=always|never|auto (checks if TTY) .........................................]     Whether or not to use colored output

Help options:
  -?, --help                                                                                

Show this help message
    --usage
Display brief usage message

什么给了?我在 C 规范中遗漏了什么吗? popt man pages 没有指定所需的长度。这是一个错误吗?

【问题讨论】:

  • 你是什么意思"What gives?"???
  • @barakmanos 是a term,基本上意味着“这是为什么?”。

标签: c segmentation-fault popt


【解决方案1】:

你的问题是别的。您已将 arg 成员设置为常量字符串,而您需要将其设置为指向此类的指针(手册页说,应该使用指向 char * 的指针初始化 arg)。您的程序在尝试取消引用不是一个指针时死掉了。

试试这样:

char *garg = "auto";

struct poptOption options[] = {
    POPT_AUTOHELP
    {
        .longName = "color",
        .shortName = '\0',
        .argInfo = POPT_ARG_STRING
                | POPT_ARGFLAG_OPTIONAL
                | POPT_ARGFLAG_SHOW_DEFAULT,
        .arg = &garg, 
        .val = 1,
        .descrip = "Whether or not to use colored output",
        .argDescrip = "always|never|auto (checks if TTY)"
    },
    POPT_TABLEEND
};

【讨论】:

  • 哦,哇,我不知道我是怎么错过的。谢谢!不知道谁对你投了反对票。我想知道为什么字符串长度会有所不同。一定是他们在内部映射数据的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2021-11-21
  • 2011-10-20
  • 2011-07-01
  • 2022-07-21
  • 1970-01-01
相关资源
最近更新 更多