Question

[Found a doublicate here: C++ - detect out-of-range access ]

If I have a programm with "out of range vector access", like this:

  std::vector<int> A(2);
  ...
  A[10] = 3;

Do I have a way to find this error for sure? I mean something like compile in debug mode and see whether some assertion stops the execution.

Up to now I have checked it by my own. But may be I don't have to write additional code?


P.S. I checked assertion of course. It doesn't called.

With this program:

#include <vector>

int main() {
  std::vector<int> A(2);
  A[10] = 3;
  return 0;
}

compiled by

g++ 1.cpp -O0; ./a.out

So it looks like std doesn't have assertion in the code, I can't stop wonder why they don't make such a simple check.

Was it helpful?

Solution

Use at() member function:

std::vector<int> A(2);

A.at(10) = 3;  //will throw std::out_of_range exception!

Since it may throw exception, you would like to catch it. So use try{} catch{} block!

Hope that helps.

OTHER TIPS

Do I have a way to find this error for sure? I mean something like compile in debug mode and see whether some assertion stops the execution.

Valgrind easily catches these errors. Just run:

valgrind ./YOUR_EXECUTABLE

I can't stop wonder why they don't make such a simple check.

See this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top