In clang, is there a way to enable bounds checking for [] access to std::vectors and other STL containers, preferably when building in debug mode only?
I just spent hours hunting down a subtle bug that turned out to be caused by us accessing past the end of a std::vector. It doesn't need to do anything clever when it detects the error, just trap in the debugger so that I can find out where it happened and fix it in the code.
Is there a way to do this other than "create your own type that inherits from std::vector", which I'd like to avoid?
(I'm using clang version 3.1 if that makes a difference.)
libstdc++
has a mature debug mode using -D_GLIBCXX_DEBUG
.
libc++
also has a debug mode using -D_LIBCPP_DEBUG
but as we can see this mailing list discussion: Status of the libc++ debug mode it is incomplete:
| My understanding is that this work was never completed and it's probably broken/incomplete.
That is correct. It’s on my list of things to fix/implement, but it’s not something that I will get to anytime soon.
It does seem to work for std::vector
on 3.4
and up see it live, give the following program:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v = {0,1,2,3} ;
std::cout << v[-1] << std::endl ;
}
it generates the following error:
vector[] index out of bounds
Aborted
If you're using Linux or OS X you should look into the address sanitizer:
http://clang.llvm.org/docs/AddressSanitizer.html
It introduces a 2x slowdown, but does a bunch of memory checking and may catch your bug.
Another amazing tool that has saved me countless times is valgrind. If you can run with valgrind it will catch a ton of memory bugs and leaks.
#define _GLIBCXX_DEBUG
This enables all kinds of inline checking (see vector and debug/vector)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With