How to check for std::vector out of range access
Asked Answered
D

2

5

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

Descender answered 6/11, 2013 at 19:48 Comment(1)
possible duplicate of C++ - detect out-of-range accessDescender
I
14

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.

Irinairis answered 6/11, 2013 at 19:50 Comment(6)
www.google.com --> c++ out of range exception --> cplusplus.com/reference/stdexcept/out_of_rangeIngmar
@stellarossa: That is a bad site. Use this instead : en.cppreference.com/w/cpp/container/vector/atIrinairis
@Nawaz: i know. the point is, it's literally the first hit you get on google when you search for the problem, and it even gives you an example. i don't understand why people don't try that first. in fact, if you search for OP's exact question "How to check for std::vector out of range access" - guess what?Ingmar
@stellarossa, oh, "How to check for std::vector out of range access" is almost exactly what I need. Thank you!Descender
@klm123: no worries, just try googling before posting here; whatever problem you have (especially if it's a beginner's problem), there's likely a solution on the net :)Ingmar
@stellarossa, well, I found at() function. But I was not satisfied with it. I am not a guru of google...:)Descender
S
2

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.

Squinteyed answered 8/12, 2014 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.