boostorg / container

STL-like containers from Boost
http://www.boost.org/libs/container/
Boost Software License 1.0
96 stars 116 forks source link

[1.85] flat_map/vector crashes on appends (memory corruption) #273

Closed Lastique closed 1 month ago

Lastique commented 2 months ago

Consider this test code:

#include <cstdint>
#include <string>
#include <boost/container/flat_map.hpp>

typedef boost::container::flat_map< std::uint8_t, std::string > my_map;

void add_element(std::string& str, char elem)
{
    str.push_back(elem);
}

int main()
{
    my_map m;
    add_element(m[static_cast< std::uint8_t >(96u)], 'a');
    add_element(m[static_cast< std::uint8_t >(102u)], 'a');
    add_element(m[static_cast< std::uint8_t >(104u)], 'a');
}
g++ -O2 -I. -std=gnu++17 -o test_flat_map test_flat_map.cpp

This crashes with:

free(): invalid pointer
Aborted (core dumped)

valgrind also shows a number of invalid memory accesses, see the attached log:

test_flat_map.log

This code works correctly in Boost 1.84.0. It also doesn't crash if compiled with -O0.

gcc 11.4.0, Kubuntu 22.04.

Lastique commented 2 months ago

Bisect shows that the first bad commit is 1a4a205ea6ef7b4e67a2faab7c7d745711807695. Reverting this commit on 1.85 (with resolved conflicts) fixes the crash.

container_revert_inline_conversion.patch.gz

igaztanaga commented 2 months ago

Thanks for the report!

I think the issue is produced because flat_map used UB in the implementation, long ago, when C++03 compilers had no movable std::pair type and the class was designed to achieve move emulation in those compilers. The following commit should fix the issue, your example seems to work after the commit, but I didn't want to close the issue without having your feedback:

https://github.com/boostorg/container/commit/20ad12f20e661978e90dc7f36d8ab8ac05e5a5a9

Lastique commented 2 months ago

Thanks, the commit does fix the problem.

It is probably worth attaching this patch to the 1.85.0 release notes.

igaztanaga commented 1 month ago

Closing this issue as fixed.