Today I debugged a crash bug of C++
program, and the core dump is like this:
Program terminated with signal SIGABRT, Aborted.
#0 0x00007f57ba2ed860 in raise () from /usr/lib/libc.so.6
(gdb) bt
#0 0x00007f57ba2ed860 in raise () from /usr/lib/libc.so.6
#1 0x00007f57ba2eeec9 in abort () from /usr/lib/libc.so.6
#2 0x00007f57ba330437 in __libc_message () from /usr/lib/libc.so.6
#3 0x00007f57ba336d34 in malloc_printerr () from /usr/lib/libc.so.6
#4 0x00005593dc2f7b6c in __gnu_cxx::new_allocator<int>::deallocate (this=0x7ffc65848820, __p=0x5593dce6fac0)
at /usr/include/c++/7.2.1/ext/new_allocator.h:125
#5 0x00005593dc2f7a36 in std::allocator_traits<std::allocator<int> >::deallocate (__a=..., __p=0x5593dce6fac0, __n=12)
at /usr/include/c++/7.2.1/bits/alloc_traits.h:462
#6 0x00005593dc2f789a in std::_Vector_base<int, std::allocator<int> >::_M_deallocate (this=0x7ffc65848820,
__p=0x5593dce6fac0, __n=12) at /usr/include/c++/7.2.1/bits/stl_vector.h:180
#7 0x00005593dc2f7543 in std::_Vector_base<int, std::allocator<int> >::~_Vector_base (this=0x7ffc65848820,
__in_chrg=<optimized out>) at /usr/include/c++/7.2.1/bits/stl_vector.h:162
#8 0x00005593dc2f71cf in std::vector<int, std::allocator<int> >::~vector (this=0x7ffc65848820,
__in_chrg=<optimized out>) at /usr/include/c++/7.2.1/bits/stl_vector.h:435
......
From the stack trace, we can see the abort()
occurred in vector
‘s destructor function. After some debugging, I find the root cause is the general “out-of-bound” error, which accessed the memory beyond the vector
space. But the caveat is that “out-of-bound” error may be silent and give you no hurt apparently. E.g., I write a simple test program:
#include <vector>
void fun() {
std::vector<int> v(1);
auto it = v.begin();
for (int i = 0; i < 100; i++) {
*it++ = i;
}
}
int main() {
fun();
return 0;
}
Build and run it:
# g++ -g test.cpp
# ./a.out
# ./a.out
The application goes well. So we really should pay enough attention to vector
access.