I have some pieces of C++ code that when run on Xcode with Undefined Behaviour Sanitizer turned on reports: "runtime error: store to misaligned address 0x7f8bcc403771 for type 'int', which requires 4 byte alignment
".
So I created a small Catch2 test case to reproduce the code I have to check the runtime behaviour on both windows/x64 (MSVC) and Mac(Xcode 11/clang) but everything runs as expected even when compiled with the different types of optimisations (-O2, -O3, -Ofast, etc).
The code in question is (Catch2 test case):
TEST_CASE("misaligned_write", "[demo]") {
unsigned char *data = (unsigned char*)malloc(20);
memset(data, 0, 20);
int *ptr = reinterpret_cast<int*>(&data[1]);
*ptr = 0x11223344; // undefined behaviour triggered
CHECK(static_cast<uint8_t>(data[1]) == 0x44);
CHECK(static_cast<uint8_t>(data[2]) == 0x33);
CHECK(static_cast<uint8_t>(data[3]) == 0x22);
CHECK(static_cast<uint8_t>(data[4]) == 0x11);
}
So my question is: is this a undefined behaviour false positive or there's something in the code that could break in the future due to some changes on default compiler flags?