为什么gdb一直将optarg显示为0x0

Duk*_*uke 5 c gdb getopt getopt-long

我正在学习如何使用getopt和*getopt_long*.一个问题是,当我使用gdb逐步运行以下简单程序时,optarg始终为0x0.
你知道为什么吗?这是gdb的问题吗?
我试图搜索网络并查看程序的汇编代码,但尚未找到答案.
调试代码表明optarg按预期指向agv [3](值"16").

#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
static struct option options[] =
{
  /* name     has_arg flag  val */
  { "num",  1, NULL, 'n' },
  { NULL ,  0, NULL , 0  }
};

int main(int argc, char** argv)
{
  int option;
  option = getopt_long( argc, argv, "n:", options, NULL );
  if (option == 'n') {
    printf("%s\n", optarg);
    if (optarg == NULL)
      printf("optarg == NULL\n");
    if (optarg == 0)
      printf("optarg == 0\n");
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在gdb上:

    (gdb) run -n 16
    Starting program: /home/ducalpha/clang/misc/a.out -n 16
...
    16          printf("%s\n", optarg);
    (gdb) p optarg
    $1 = 0x0
Run Code Online (Sandbox Code Playgroud)

输出:

$ ./a.out -n 16
16
Run Code Online (Sandbox Code Playgroud)

wal*_*lyk 0

(针对修改后的问题修改后的答案)

这个对我有用。输出是:

Reading symbols from /home/wally/a.out...done.
(gdb) run -n 16
Starting program: /home/wally/a.out -n 16
16
[Inferior 1 (process 10999) exited normally]
Run Code Online (Sandbox Code Playgroud)

  • @Duke:你是对的。gdb 检查“optarg”时发生了一些非常奇怪的事情。这似乎是一个符号管理问题,可能与运行时库的特性有关。在这种情况下,使用 printf() 进行调试优于使用调试器。 (2认同)