According to Wikipedia and this, this code is undefined behavior:
#include <iostream>
int main(int, char**) {
int data[1] = {123};
int* p = data + 5; // undefined behavior
std::cout << *(p - 5) << std::endl;
}
Compiled with clang++-6.0 -fsanitize=undefined
and executed, the undefined behavior is detected which is fantastic, I get this message:
ub.cpp:5:19: runtime error: index 5 out of bounds for type 'int [1]'
But when I don't use an array, the undefined behavior is not detectable:
#include <iostream>
int main(int, char**) {
int data = 123;
int* p = &data + 5; // undefined behavior
std::cout << *(p - 5) << std::endl;
}
The sanitizer detects nothing, even though this is still undefined behavior. Valgrind also does not show any problem. Any way to detect this undefined behavior?
Since I am never accessing any invalid data, this is not a duplicate of Recommended way to track down array out-of-bound access/write in C program.