If I understand Why is out-of-bounds pointer arithmetic undefined behaviour? correctly, this program has undefined behaviour:
#include <iostream>
int main(int, char**) {
int a = 0;
// out of bounds pointer: undefined behavior?
uint8_t* ptr = reinterpret_cast<uint8_t*>(&a) - 1;
*(ptr + 2) = 0xff;
std::cout << std::hex << a << std::endl;
}
Is there any way to detect this undefined behaviour? I've tried sanitizers -fsanitize=undefined
with g++-8 and clang-8, and more warnings with -Wall -Wextra
, in clang++ I've also tried -Warray-bounds-pointer-arithmetic -Warray-bounds
but non print any warnings whatsoever.
EDIT: I am never accessing or writing to any data outside the valid range. So it's not a duplicate of Recommended way to track down array out-of-bound access/write in C program.