2

I build the program below with g++ (g++ - g3 main.cpp) and VisualStudio 2013 (VS) in debug mode.When run - VS exits with assert complaining about index range issue but g++ version under Ubuntu 13.10 runs fine and it prints vi[11] = 11.

I understand - C++ Standard does not specify behavior for my case but warning or crash in my case would be nice.

Is there any flag in gcc(or clang) to enable array index out of range check during build ? If no is any good analysis tool for that ?

int main() { 
    vector<int> vi(8); 
    vi.push_back(1); 
    vi.push_back(2); 

    vi[11] = 11; 
    std::cout << "Vi[11]=" << vi[11] << std::endl; 

    return 0; 
}
Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
user2890398
  • 139
  • 1
  • 1
  • 4
  • This looks like a duplicate of http://stackoverflow.com/questions/4778552/is-it-possible-to-enable-array-bounds-checking-in-g – Jerry Jeremiah Nov 21 '13 at 23:15
  • This looks quite helpful: http://stackoverflow.com/questions/2291114/runtime-array-bounds-checking-with-g – Jerry Jeremiah Nov 21 '13 at 23:16
  • @JerryJeremiah Yes, it does. – Ali Nov 21 '13 at 23:57
  • Apart from the tools recommended on the above links, you might consider accessing your array elements with as `vi.at(11)`. In this case, an exception is thrown on the line violating the bound. It does have a performance penalty though... – Ali Nov 21 '13 at 23:59
  • Possible duplicate of [GCC STL bound checking](https://stackoverflow.com/questions/5594686/gcc-stl-bound-checking) – underscore_d Sep 19 '17 at 10:06

1 Answers1

0

There is a nice tool for bounds check: http://cppcheck.sourceforge.net/ Regarding gcc -Warray-bounds flag may help.

Igor Popov
  • 2,588
  • 17
  • 20