c++stlg++

STL push_back optimize cause array subscript is above array bounds


Test environment:

Compile command cases:

  1. PASS: g++ -Wall t.cpp
  2. FAIL: g++ -Wall -O2 t.cpp
  3. PASS: g++ -Wall -O2 t.cpp # and replace 2 with 3 on line 13
  4. PASS: g++ -Wall -O2 t.cpp # and comment out line 14
  5. PASS: g++ -Wall -O2 --std=c++11 t.cpp # for g++ 4.8/4.9

The FAIL message:

t.cpp: In member function ‘void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vecto
<_Tp, _Alloc>::iterator, const _Tp&) [with _Tp = Object; _Alloc = std::allocator<Ob
ject>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<Object*, s
td::vector<Object> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = Object*]’
t.cpp:17:15: warning: array subscript is above array bounds [-Warray-bounds]
     ~Object() {};
               ^
t.cpp:17:15: warning: array subscript is above array bounds [-Warray-bounds]

t.cpp

#include <vector>                      
class TestCls {                        
public:                                
    TestCls() {};                      
    virtual ~TestCls() {};             
};                                     
class TestCls1 : public TestCls        
{                                      
};                                     
class Object {                         
public:                                
    TestCls    m_member[2];            
    TestCls1   m_member1[2]; // LINE 13, if change to [3] it works.
    TestCls1   m_member2[2]; // LINE 14, if comment out this line, it works.

    Object() {};                       
    ~Object() {}; // LINE 17 the warning line                     
};                                     
class Container {                      
public:                                
    std::vector<Object> m_obj;         

    Container() {};                    
    ~Container() {};                   
};                                     
int main() {                           
        Container con;                 
        Object obj;                    
        con.m_obj.push_back(obj);      
}                                      

Solution

  • I found a solution, but I don't know the reason.

    // ...
    class Object {
    public:
        // ...
        ~Object();
    };
    Object::~Object() {}; // move to outside LINE 19
    //...