3

I would like to analyse my C++ code to find bad access in vectors and arrays (out of range access), is there a tool for that ?

thanks in advance

Shnippoo
  • 193
  • 2
  • 10
  • 2
    Most c++ implementations come with a checked standard library implementation, have you checked the documentation of yours? – PlasmaHH Sep 21 '11 at 09:39
  • 2
    Well written code is the start -- add assertions liberally. At runtime, you can use `valgrind` to check for invalid memory access. – Kerrek SB Sep 21 '11 at 09:41
  • 2
    You can "assert" your code. For vector you can replace [] with at() that will throw an exception instead of undefined behaviour. – Alessandro Teruzzi Sep 21 '11 at 09:42

4 Answers4

10

You can compile with _GLIBCXX_DEBUG and _GLIBXX_DEBUG_PEDANTIC defined if your are using gcc. This will enable glibc assertions to be raised if out of bounds access is requested.

Testing with valgrind::memcheck will also reveal bad memory reads

Marios V
  • 1,174
  • 9
  • 15
  • 1
    Those flags are pretty useful but I've recently found a case where they produce **segfaults**. If you try to use them along with the **boost regex** library your program will fail. I can't imagine why this happens or what else is affected. See https://svn.boost.org/trac/boost/ticket/5911 for details – Pan. Christopoulos Charitos Dec 09 '11 at 09:04
  • @P.ChristopoulosCharitos this happens because, as said in the ticket, Boost.Regex is compiled with normal ABI, while `_GLIBCXX_DEBUG` changes it, thus the app using it crashes due to ABI mismatch. – Ruslan Jan 08 '16 at 16:37
6

Yes: Valgrind.

And many others: http://en.wikipedia.org/wiki/Memory_debugger.

Note also that most implementations of e.g. std::vector have a debug mode where they will do run-time bounds checking.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

There are some paid tools, which does static analysis:

klockwork

coverity

IBM Rational Purify does dynamic analysis.

iammilind
  • 68,093
  • 33
  • 169
  • 336
0

create a class on you arrays and create some controlling functions in that class with operators and .... then use this class .

sam
  • 1,363
  • 1
  • 20
  • 32