boost::serialization
contains this code:
reinterpret_cast<std::ptrdiff_t>(
static_cast<Derived *>(
reinterpret_cast<Base *>(1 << 20)
)
) - (1 << 20)
Its purpose is to calculate an offset between base and derived classes. Is this code free of undefined behaviour?
The reason why I am asking is that ASAN+UBSAN complain. For example, this code
#include <iostream>
class Foo { public: virtual void foo() {} };
class Base { public: virtual void base() {} };
class Derived: public Foo, public Base {};
int main()
{
std::cout <<
(reinterpret_cast<std::ptrdiff_t>(
static_cast<Derived *>(
reinterpret_cast<Base *>(1 << 20)
)
) - (1 << 20));
}
compiled as (gcc version 9.2.1)
g++ -fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer -g main.cpp
produces this output
AddressSanitizer:DEADLYSIGNAL
=================================================================
==72613==ERROR: AddressSanitizer: SEGV on unknown address 0x0000000ffff8 (pc 0x0000004012d9 bp 0x7ffd5b3eecf0 sp 0x7ffd5b3eece0 T0)
==72613==The signal is caused by a READ memory access.
#0 0x4012d8 in main main.cpp:13
#1 0x7f74a90d5f42 in __libc_start_main (/lib64/libc.so.6+0x23f42)
#2 0x40112d in _start (/home/.../a.out+0x40112d)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV main.cpp:13 in main
Is it a false-positive or does this code really have problems?
Update 09.12.2019: based on Filipp's proposal and my experiments, this code seems to work and does not produce any warnings:
std::aligned_storage<sizeof(Derived)>::type data;
reinterpret_cast<char*>(&data)
- reinterpret_cast<char*>(
static_cast<Base*>(
reinterpret_cast<Derived*>(&data)));
Does anybody see any problems with this snippet? If not, I would propose it to boost
.
Update 16.12.2019: the fix was merged to boost::serialization
develop
branch.