Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a c++ object members using GDB from an address if the object's class type is like A::B [duplicate]

Tags:

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;

}

like image 741
Gary Hu Avatar asked Sep 11 '11 17:09

Gary Hu


People also ask

What does print do in GDB?

The usual way to examine data in your program is with the print command (abbreviated p ), or its synonym inspect . It evaluates and prints the value of an expression of the language your program is written in (see section Using GDB with Different Languages). expr is an expression (in the source language).

How do I set variables in GDB?

The expression can be any expression that is valid in the current context. The set variable command evaluates the specified expression. If the expression includes the assignment operator ( = ), the debugger evaluates that operator, as it does with all operators in expressions, and assigns the new value.

What does incomplete type mean in GDB?

It means that the type of that variable has been incompletely specified. For example: struct hatstand; struct hatstand *foo; GDB knows that foo is a pointer to a hatstand structure, but the members of that structure haven't been defined. Hence, "incomplete type".


1 Answers

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;

like image 181
Matt Avatar answered Sep 16 '22 17:09

Matt