Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak during unordered_map::insert KeyEqual exception with GCC - breaking the strong exception safety guarantee?

I'm using GCC 7.3.1, but also tested on coliru, which I believe is version 9.2.0. Build with the following:

g++ -fsanitize=address -fno-omit-frame-pointer rai.cpp

Here's rai.cpp:

#include <iostream>
#include <unordered_map>

int main()
{
    try
    {
        struct MyComp {
            bool operator()(const std::string&, const std::string&) const {
                throw std::runtime_error("Nonono");
            }
        };

        std::unordered_map<std::string, std::string, std::hash<std::string>, MyComp> mymap;
        mymap.insert(std::make_pair("Hello", "There"));
        mymap.insert(std::make_pair("Hello", "There")); // Hash match forces compare
    } catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << "\n";
    }
}

Running it results in:

> ./a.out
Caught exception: Nonono

=================================================================
==72432==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 32 byte(s) in 1 object(s) allocated from:
...

Direct leak of 4 byte(s) in 1 object(s) allocated from:
...

Indirect leak of 60 byte(s) in 2 object(s) allocated from:
...

SUMMARY: AddressSanitizer: 96 byte(s) leaked in 4 allocation(s).

I don't see any memory leaks with Visual C++ (Microsoft (R) C/C++ Optimizing Compiler Version 19.24.28314 for x64).

Does this break the strong exception safety guarantee of unordered_map::insert (https://stackoverflow.com/a/11699271/1958315)? Is this a bug in the GCC STL?

like image 899
Rai Avatar asked Dec 12 '19 14:12

Rai


1 Answers

The guarantee mandated by the standard (quotes from latest draft):

[container.requirements.general]

Unless otherwise specified (see [associative.reqmts.except], [unord.req.except], [deque.modifiers], and [vector.modifiers]) all container types defined in this Clause meet the following additional requirements:

  • if an exception is thrown by an insert() or emplace() function while inserting a single element, that function has no effects.

[associative.reqmts.except]

For associative containers, if an exception is thrown by any operation from within an insert or emplace function inserting a single element, the insertion has no effect.

[unord.req.except]

For unordered associative containers, if an exception is thrown by any operation other than the container's hash function from within an insert or emplace function inserting a single element, the insertion has no effect.

As far as I understand, "has no effect" implies "no memory leak". Under such interpretation, I would consider a leak to be a bug.

like image 198
eerorika Avatar answered Sep 28 '22 08:09

eerorika