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