Description
A C++ application creating an object in shared memory crashes due to a segmentation violation when
the application is compiled with -O2 or -O3. When compiling without the -O2 or -O3, the application works correctly.
See below for the file tests.cc which is a part of a unit test using the Boost unit test framework.
The crash occurs has been seen both when using Boost 1.65 and Boost 1.78.
Could you please help me to find the reason for this crash?
Please see various info related to this issue below.
Building the executable file
g++ -O3 -c tests.cc -o tests.o
g++ tests.o -lboost_unit_test_framework -lpthread -lrt -o unit_tests
Output when crashing (compiled with -O2 or -O3)
./unit_tests
Running 1 test case...
unknown location(0): fatal error: in "test_1": signal: SIGSEGV, si_code: 128 (memory access violation at address: 0x00000000)
tests.cc(66): last checkpoint: "test_1" test entry
*** 1 failure is detected in the test module "shm_comm"
Output when compiling without -O2 and -O3
./unit_tests
Running 1 test case...
*** No errors detected
Compiler version
gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)
File tests.cc
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE shm_comm
#include <boost/test/included/unit_test.hpp>
#include
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bip = boost::interprocess;
constexpr int CACHE_LINE_SIZE = 64;
class S
{
class AQC
{
public:
alignas(CACHE_LINE_SIZE) std::atomic head_ = {};
};
class AQ : public AQC
{
public:
alignas(CACHE_LINE_SIZE) std::atomic<uint64_t> elements_[3] = {};
};
public:
static S& getInstance()
{
static S instance;
return instance;
}
bool f(void)
{
bip::shared_memory_object::remove("abc");
int number_of_bytes_in_shm = sizeof(AQ);
// Add space for other areas. This is not clear exactly what this is used for and its exact size.
number_of_bytes_in_shm += 600;
// Create a shared memory segment
mSegment = new bip::managed_shared_memory(bip::create_only, "abc", number_of_bytes_in_shm);
mAQ = mSegment->construct<AQ>("AQ")();
return true;
}
S(S const&) = delete;
void operator=(S const&) = delete;
private:
S() {}
~S() {}
bip::managed_shared_memory* mSegment;
AQ* mAQ;
};
BOOST_AUTO_TEST_CASE(test_1)
{
S& s = S::getInstance();
bool f = s.f();
BOOST_CHECK(f == true);
}