5

I am learning how getopt and *getopt_long* work. One problem is that when I use gdb to run the following simple program step by step, the optarg is always 0x0.
Do you know why?Is it the problem of gdb?
I tried to search the web and look at the program's assembly code but found no answer yet.
The debugging 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;
}

On 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

Output:

$ ./a.out -n 16
16
Duke
  • 1,332
  • 12
  • 12
  • 1
    There already exists a bug report related to this issue: http://sourceware.org/bugzilla/show_bug.cgi?id=13800 – alk Sep 07 '12 at 12:36

1 Answers1

0

(revised answer in response to revised question)

It works for me. The output is:

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]
wallyk
  • 56,922
  • 16
  • 83
  • 148
  • Sorry, I forgot to say that I executed the program in gdb with "run -n 16". I did not include the loop for simplicity. – Duke Sep 07 '12 at 03:13
  • Well, the normal run works as expected. However, I wonder why gdb displays optarg value as 0x0 when I stepped through the program. – Duke Sep 07 '12 at 03:28
  • @Duke: if you did not set the program arguments (with `set args -n 16`), there would be none for the program to process. To step the program you would use either the `start` command, or set a breakpoint and use the same run command. Which did you do? – wallyk Sep 07 '12 at 03:31
  • In gdb, I made a break point on main() and ran through the program using "run -n 16" – Duke Sep 07 '12 at 03:34
  • @Duke: it looks like it output `16`. Did the program exit? At what point in the execution did you examine `optarg`? – wallyk Sep 07 '12 at 04:41
  • I examined the `optarg` at line 16 `printf("%s\n", optarg);` (after the _if_ command). The program did not exit at that point. I used gdb's `next` command to reach that line. – Duke Sep 07 '12 at 04:50
  • 2
    @Duke: You are correct. There is something very odd going on with gdb examining `optarg`. It appears to be a symbol management issue, perhaps related to the runtime library's characteristics. This is a situation where debugging using `printf()` is superior to using a debugger. – wallyk Sep 07 '12 at 05:47