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

冷暖自知 提交于 2019-12-01 16:02:16

问题


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


回答1:


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.




回答2:


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




回答3:


#define _GLIBCXX_DEBUG

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



来源:https://stackoverflow.com/questions/16467380/bounds-checking-of-stdvector-and-other-containers-in-clang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!