我在调试期间注意到,在调试期间,GNU的optarg变量的盖托特仍然是zero (即地址0x0)。但是,当optarg用作赋值的右操作数或作为参数传递参数时,将应用期望值。GNU的例子:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c': # b 26
cvalue = optarg; # gdb stops right before executing this line
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("aflag = %d, bflag = %d, cvalue = %s\n",
aflag, bflag, cvalue);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}使用
$ gcc -o getopt getopt.c -g # debugging ON, optimizations OFF
$ gdb getopt
(gdb) b 26 # set breakpoint
(gdb) r -cfoo
(gdb) p optarg
$1 = 0x0 # no "foo"?
(gdb) n # executes cvalue = optarg
(gdb) p cvalue
$2 = 0x7fffffffea99 "foo" # here it is, please don't expect to get the same memory-address为什么optarg不包含第26行的字符串"foo“?我在这里错过了什么?
更令人困惑的是,我发现即使行已经执行,它也不包含"foo“。我看了一下原始源,没有注意到编译器优化之类的东西。我使用GCC 11.1.0在Archlinux,x86_64上。
谢谢
https://stackoverflow.com/questions/69409047
复制相似问题