'how to view std:unordered_map member in GDB

When trying to access a member of std::unordered_map using [], I get an error:

Attempt to take address of value not located in memory.

There is a nice gdb-stl-views, except it does not support unordered_map.

Is there a similarly nice way to retrieve by key a member of unordered_map?



Solution 1:[1]

I think you are capable of viewing the member of std::unordered_map with an additional trivial step:

This is my test code:

#include <iostream>
#include <unordered_map>

std::string make_key(const char *input) { return input; }// The additional function to make sure you could construct the key of your map in gdb from primitive type

int main(int argc, char **argv) {
      std::unordered_map<std::string, int> map = {
                {"bar", 100}
             };

        std::cout << map.at("bar");
}

And I am using gdb 11.2 in Archlinux:

g++ -std=gnu++11 -O0 -g unordered_map_test.cpp -o unordered_map_test

gdb unordered_map_test
(gdb) p map
$1 = std::unordered_map with 1 element = {["bar"] = 100} 

// Perhaps it's useless to print all key-value pairs in map if you have a large map.

// Then you could print value of specific key

(gdb) p map.at(make_key("bar"))
$2 = (std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::hash<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int> > >::mapped_type &) @0x55555556eed8: 100 // 100 is the value of `bar`

// If you think it's annoying that there is too much type information above, you could just print the value after you know the address of value.

(gdb) p *0x55555556eed8
$3 = 100

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ramsay