This simply creates some list elements, then deletes an element at its beginning approaching it via reverse iteration. It's a replica of an actual problem with the code which deletes elements while traversing them in reverse.
#include <list>
int main()
{
std::list< int > lst;
for ( int c = 33; c--; )
lst.push_back( 0 );
int count = 0;
for ( std::list< int >::reverse_iterator i = lst.rbegin(), e = lst.rend();
i != e; )
{
switch( count++ )
{
case 32:
case 33:
++i;
i = std::list< int >::reverse_iterator( lst.erase( i.base() ) );
break;
default:
++i;
}
}
return 0;
}
When run, it crashes with:
*** glibc detected *** ./a.out: double free or corruption (out): 0x00007fff7f98c230 ***
When run with valgrind, it says:
==11113== Invalid free() / delete / delete[] / realloc()
==11113== at 0x4C279DC: operator delete(void*) (vg_replace_malloc.c:457)
==11113== by 0x40104D: __gnu_cxx::new_allocator<std::_List_node<int> >::deallocate(std::_List_node<int>*, unsigned long) (in /tmp/a.out)
==11113== by 0x400F47: std::_List_base<int, std::allocator<int> >::_M_put_node(std::_List_node<int>*) (in /tmp/a.out)
==11113== by 0x400E50: std::list<int, std::allocator<int> >::_M_erase(std::_List_iterator<int>) (in /tmp/a.out)
==11113== by 0x400BB6: std::list<int, std::allocator<int> >::erase(std::_List_iterator<int>) (in /tmp/a.out)
==11113== by 0x40095A: main (in /tmp/a.out)
Compiler:
$ g++ --version
g++ (Debian 4.7.1-7) 4.7.1
Arch:
$ uname -a
Linux hostname 3.2.0-2-amd64 #1 SMP Mon Apr 30 05:20:23 UTC 2012 x86_64 GNU/Linux
Do you think it's a bug, or am I doing something wrong here?
p.s. If you remove case 33
(which should never happen), this turns into an infinite loop instead of a crash.