0

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.

martinus
  • 17,736
  • 15
  • 72
  • 92
  • Best bet is using an SCA tool. – πάντα ῥεῖ Apr 25 '19 at 17:24
  • [Valgrind](http://valgrind.org) and friends. It's worth noting that when you're doing a `reinterpret_cast` you're assuming a *lot* of responsibility for getting your code right. C++ basically assumes you know what you're doing when you use a tool like that and won't get in your way if you're using it completely wrong. – tadman Apr 25 '19 at 17:24
  • 1
    Where exactly do you have UB in the posted code? – NathanOliver Apr 25 '19 at 17:25
  • 1
    valgrind doesn't show any problem either. I'm never *accessing* any data outside the valid range. – martinus Apr 25 '19 at 17:26
  • "Is there any way to detect this undefined behaviour?" - Yes. Knowing the language standard *intimately* and then *carefully* reading the code is one way. – Jesper Juhl Apr 25 '19 at 17:26
  • What if you do access outside the valid range? Like `ptr[9999] = 0`? Remember, pointers and arrays are largely interchangeable, so instead of `*(ptr + 2) = x` do `ptr[2] = x`. – tadman Apr 25 '19 at 17:26
  • @πάνταῥεῖ this is not a duplicate because I am never *accessing/writing* to any invalid area. – martinus Apr 25 '19 at 17:32
  • @martinus You do not have any undefined behavior. It is legal in C/C++ to use a pointer which is not the exact start of your data. Actually, I worked at a company where some people loved FORTRAN so much that they would allocate a buffer and then save that pointer - 1. Then they could access their data with `ptr[1]` to `ptr[size]`. It's legal. Just rather weird for a _normal_ C/C++ programmer. – Alexis Wilke Apr 26 '19 at 04:22
  • It is illegal, and was the source of a very hard to catch bug on an exotic hardware with an old compiler – martinus Apr 26 '19 at 15:33

0 Answers0