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[] =
{
{ "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
source
share