-6

I am doing a simple program that tries to fetch a non-existent key-value pair in the map. But when I run the code, I get a runtime error saying ==8406==WARNING: AddressSanitizer failed to allocate 0x7ffe7f82c881 bytes ==8406==AddressSanitizer's allocator is terminating the process instead of returning 0 ==8406==If you don't like this behavior set allocator_may_return_null=1

#include <iostream>
#include <map>
#include <string>

int main ()
{
    typedef std::map<std::string,int> mymap;
    mymap cnt;

    cnt["a"]=10;

    auto f = first.find("asdasd");
    std::cout << f->second;
    return 0;
}

at line where I do f->second. How could I handle the case where the key does not exist in the map?

Amanda
  • 2,013
  • 3
  • 24
  • 57

2 Answers2

3

Assuming you mean

auto f = cnt.find("asdasd");

you need to check if the key that you looked for actually exists

if (f != cnt.end())
    std::cout << f->second;

Otherwise you are dereferencing an invalid location, and that's UB.

cigien
  • 57,834
  • 11
  • 73
  • 112
3

The find member function of std::map specializations returns a past-the-end iterator if the key does not exist.

So you need to compare to the container's end():

 auto f = cnt.find("asdasd");
 if (f != cnt.end()) {
     std::cout << f->second;
 }
aschepler
  • 70,891
  • 9
  • 107
  • 161