0

Using GDB, I want to access member variable pointers of an element in a map to inspect values of the object referred by the said pointer.

Consider the below program.

#include <iostream>
#include <map>

struct Parent
{
    std::string phone_number;
    Parent(std::string num): phone_number(num){}
};

struct Student
{
    int student_id;
    std::string student_name;
    Parent* parent = nullptr;

    Student(int id, std::string name):student_id(id), student_name(name) {}

};

int main()
{
    Parent* p_tim = new Parent("0712323456");
    Parent* p_tom = new Parent("0112122123");

    Student ann(1, "Anne");
    Student bobby(2, "Bobby");

    ann.parent = p_tim;
    bobby.parent = p_tom;

    std::map<std::string, Student> students;
    students.insert(std::make_pair("ann", ann));
    students.insert(std::make_pair("bob", bobby));

    for(auto student:students)
    {
        std::cout << "Student: ID = " << student.second.student_id << " and Name: " << student.second.student_name << std::endl;
    }

    return 0;
}

I can view the contents of the map using the following command.

(gdb) p students
$1 = std::map with 2 elements = {["ann"] = {student_id = 1,
    student_name = "Anne", parent = 0xa85ed0}, ["bob"] = {student_id = 2,
    student_name = "Bobby", parent = 0xa85f20}}

I want to inspect the parent object inside a single element in the map. For example, I want to inspect the phone number of ann's parent from this map. But I cant access it like below.

(gdb) p students["ann"].parent->phone_number
Could not find operator[].

Can you please let me know how this is done in GDB?

I think it should be possible(from command line GDB) because the visual debugger in VS Code shows this information. enter image description here

Pasan W.
  • 674
  • 2
  • 10
  • 23
  • Does [this](https://stackoverflow.com/questions/427589/inspecting-standard-container-stdmap-contents-with-gdb?rq=1) answer the question? – Jérôme Richard Mar 15 '20 at 21:05

1 Answers1

2

Can you please let me know how this is done in GDB?

You could always do this: (gdb) p *(Parent*) 0xa85ed0.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362