首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么getopt的optarg变量在调试过程中为零?

为什么getopt的optarg变量在调试过程中为零?
EN

Stack Overflow用户
提问于 2021-10-01 16:16:58
回答 1查看 157关注 0票数 1

我在调试期间注意到,在调试期间,GNU的optarg变量的盖托特仍然是zero (即地址0x0)。但是,当optarg用作赋值的右操作数或作为参数传递参数时,将应用期望值。GNU的例子:

代码语言:javascript
复制
#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;
}

使用

代码语言:javascript
复制
$ 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上。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-10-18 17:37:41

PaulMcKenzie似乎是对的。可能是GDB中的这个旧虫8588。GDB很难处理得到 (全局偏移表)权限,这是图图 (位置无关代码)的一部分。

解决方案

代码语言:javascript
复制
p (char*)'optarg@GLIBC_2.2.5' 

这里我们引用了optarg变量和GLIBC的版本符号。版本2.2.5是基线,它已经包含了getopt,因此新版本的getopt不适用。

谢谢

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69409047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档