检查GDB上层范围中的班级成员

examine class members in an upper scope in gdb

本文关键字:成员 范围 GDB 检查      更新时间:2023-10-16

有一个类方法,其中包含开关/情况。为了表示,

之类的东西
class class_name {
  int k;
public:
  int method();
  class_name():k(0) {}
};
int class_name::method() {
  k = 2; // class private data member, an integer
  switch(k){ 
    case 0:
      // to examine k at this point 
      // perform path A 
      break;
    case 1: 
      // perform path B 
      break;
  } // switch(k)
  return 0; 
}

问题是:如果我想从开关/情况范围内从上部范围(例如K)中检查数据。我可以总是在上部范围中的某个地方放置一个断点,例如在分配k = 2的行上?

#include <stdio.h>
struct z
{
    z() : k(42) {}
    int k;
    int mm ();
};
int z::mm()
{
    int k = 0;
    {
        int k = 1;
        {
            int k = 2;
            printf ("%dn", k);
        }
    }
}
int main()
{
    z zp;
    zp.mm();
}

当您在printf上停止时,很难在外部范围中打印变量。 up帧之间移动时不起作用,而不是 scopes 。我不知道一种简单的方法,但是有解决方法。

info locals将打印所有变量本地为函数。

(gdb) info locals
k = 2
k = 1
k = 0

这可能足以容纳简单的整数变量,但是如果我们有指针并想解释它们怎么办?

(gdb) where
#0  z::mm (this=0xbfffec8c) at q.C:18
#1  0x080484a5 in main () at q.C:26

好吧,我们在第18行,我们知道什么?

(gdb) info scope 18
Scope for 18:
Symbol k is a variable at frame base reg $ebp offset 8+-28, length 4.
Symbol k is a variable at frame base reg $ebp offset 8+-24, length 4.
Symbol k is a variable at frame base reg $ebp offset 8+-20, length 4.
Symbol this is a variable at frame base reg $esp offset 4+0, length 4.

aha,有三个名为 k的符号(无论是什么意思), $ebp看起来像寄存器名称,旁边的数字必须是偏移。

(gdb) p *(int*)($ebp+8-20)
$1 = 0
(gdb) p *(int*)($ebp+8-24)
$2 = 1
(gdb) p *(int*)($ebp+8-28)
$3 = 2

看起来我们在这里有赢家。

哦,总是可以说

(gdb) p this->k
$4 = 42

您输入以'向上'调用堆栈。呼叫将进行反向。那是你要的吗?