This code :
int *p = nullptr;
p++;
cause undefined behaviour as it was discussed in Is incrementing a null pointer well-defined?
But when explaining fellows why they should avoid UB, besides saying it is bad because UB means that anything could happen, I like to have some example demonstating it. I have tons of them for access to an array past the limits but I could not find a single one for that.
I even tried
int testptr(int *p) {
intptr_t ip;
int *p2 = p + 1;
ip = (intptr_t) p2;
if (p == nullptr) {
ip *= 2;
}
else {
ip *= -2;
} return (int) ip;
}
in a separate compilation unit hoping that an optimizing compiler would skip the test because when p
is null, line int *p2 = p + 1;
is UB, and compilers are allowed to assume that code does not contain UB.
But gcc 4.8.2 (I have no useable gcc 4.9) and clang 3.4.1 both answer a positive value !
Could someone suggest some more clever code or another optimizing compiler to exhibit a problem when incrementing a null pointer ?
See Question&Answers more detail:os