Search code examples
c++c++11unordered-mapemplace

C++11 segfault on reference to unordered_map in vector


When i run the following code I get a segfault on the 'find()' call.

#include <vector>
#include <unordered_map>

struct item {
    std::unordered_map<int,int> map;
};

int main(int argc, char** argv) {
   std::vector<item> stack;
   stack.emplace_back();
   std::unordered_map<int,int>& topmap=stack.back().map;
   stack.emplace_back();
   auto ind=topmap.find(5);
   if(ind!=topmap.end()) {
      printf("Found element five in second to top item\n");
   }
}

(compiled with -std=c++11)

However, if the second emplace_back() call is removed, there is no segfault.

Why is this? Am I using reference variables wrong? Does adding another element to the stack invalidate topmap?


Solution

  • The most likely explanation is that the second call to emplace_back causes a re-allocation, invalidating topmap. You can easily check this by looking at stack.capacity(). If that changes between calls, there has been a re-allocation.