auto vec = std::vector<int>({1, 2, 3});
std::cout << *vec.end() << std::endl;
Here is some simple code that I believe to be UB. However, compiling this with the following steps:
g++ -std=c++23 -Wall -Wextra -g -fsanitize=undefined -o ./target/src/main.cpp.o src/main.cpp
g++ -fsanitize=undefined -o ./target/main ./target/src/main.cpp.o
Results in a perfectly happy sanitizer and an output of 0!
I thought that the way contiguous collection iterators worked in C++ was that they pointed to the first out-of-bounds memory location.
{1, 2, 3} ?, ?, ?, ...
^ begin ^ end
My thinking is that the creation of any arbitrary pointer is technically safe, but the dereferencing of this pointer is what is unsafe, so this is a fine method of creating iterators. Of course, this is very unlikely to be something wrong with fsanitize so let me know where I'm going wrong! :)
You are right; this is undefined behavior, and some sanitizer should pick up on it. Clang's UBSan detects it, and GCC's ASan does:
This produces the error:
See live example at Compiler Explorer
In general, you should typically use
-fsanitize=address,undefinedto catch a wider range of errors. Alternatively, use external tools like valgrind.