Why gdb displays optarg as 0x0 all the time

I am learning how getopt and * getopt_long * work. One of the problems is that when I use gdb to execute the next simple program step by step, optarg is always 0x0.
Do you know, why? Problem with gdb ?
I tried to search the Internet and see the build code of the program, but could not find the answer.
The debug code indicates that optarg points to agv [3] (value "16") as expected.

#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;
}

In 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

Conclusion:

$ ./a.out -n 16
16
+5
source share
1 answer

(revised response to the revised question)

This works for me. Output:

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]
0
source

All Articles