Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bounds checking of std::vector (and other containers) in clang?

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.)

like image 635
Colen Avatar asked May 09 '13 17:05

Colen


3 Answers

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

like image 176
Shafik Yaghmour Avatar answered Oct 09 '22 23:10

Shafik Yaghmour


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.

like image 41
stokastic Avatar answered Oct 09 '22 23:10

stokastic


#define _GLIBCXX_DEBUG

This enables all kinds of inline checking (see vector and debug/vector)

like image 27
Ben Brammer Avatar answered Oct 10 '22 00:10

Ben Brammer