如何打印 c++如果对象的类类型类似于 A::B,则从地址使用 GDB 的对象成员
从这个链接 gdb 将内存地址解释为对象 我们知道,如果一个类类型A的对象位于特定地址,例如0x6cf010,那么我们可以使用:
(gdb) p *(A *) 0x6cf010
打印该对象的成员元素。
然而,当涉及 c++ 命名空间时,这似乎不起作用。也就是说,如果类类型为 A::B 的对象,那么以下所有尝试都不起作用:
(gdb) p *(A::B *) 0x6cf010
(gdb) p *((A::B *) 0x6cf010)
那么,谁知道如何在这种情况下打印对象元素?
我们可以使用以下有意的核心代码来尝试从地址打印 p 的成员(我们可以使用“info locals”来显示地址)。
#include <stdio.h>
namespace A
{
class B
{
public:
B(int a) : m_a(a) {}
void print()
{
printf("m_a is %d\n", m_a);
}
private:
int m_a;
};
}
int main()
{
A::B *p = new A::B(100);
p->print();
int *q = 0;
// Generating a core here
*q = 0;
return 0;
}
From this link
gdb interpret memory address as an object
we know that, if an object of class type A is at a specific address such as 0x6cf010, then we can use:
(gdb) p *(A *) 0x6cf010
to print the member elements of this object.
However, this seems doesn't work when c++ namespace is involved. That is, if the object of class type A::B, then all the following trying doesn't work:
(gdb) p *(A::B *) 0x6cf010
(gdb) p *((A::B *) 0x6cf010)
So, who knows how to print the object elements under this conditions?
We can use the following deliberate core code to try to print the members of p from the address (we can use "info locals" to show the address).
#include <stdio.h>
namespace A
{
class B
{
public:
B(int a) : m_a(a) {}
void print()
{
printf("m_a is %d\n", m_a);
}
private:
int m_a;
};
}
int main()
{
A::B *p = new A::B(100);
p->print();
int *q = 0;
// Generating a core here
*q = 0;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这被标记为已回答,但我能够在 OS X
(GNU gdb 6.3.50-20050815 (Apple version gdb-1820) (Sat Jun 16 02:40:11 UTC) 上使用 gdb 重现此问题2012))
和为我工作的解决方案没有为我解答。事实证明,SO 上还有另一个问题确实有一个有效的答案,所以我认为值得讨论这个问题:
为什么 gdb 转换不起作用?
简短的答案是您可能必须单引号命名空间变量:
(gdb) p ('MyScope::MyClass'*) ptr;
I know that this is labeled as answered, but I was able to reproduce this problem using gdb on OS X
(GNU gdb 6.3.50-20050815 (Apple version gdb-1820) (Sat Jun 16 02:40:11 UTC 2012))
and the works-for-me solution didn't answer it for me.Turns out there was another question on SO that did have an answer which worked, so I think it's worth pulling into this quesiton:
Why gdb casting is not working?
The short answer is that you may have to single-quote your namespaced variables:
(gdb) p ('MyScope::MyClass'*) ptr;
对我有用:
对我有用。你正在使用什么(gcc 版本、操作系统、编译标志?)
Works for me:
It works for me. What are you using (gcc version, OS, compilation flags?)