写入超出大小的向量会导致恐慌

时间:2013-10-02 19:57:42

标签: c++ stl

我有以下简单的C ++程序,它使用STL中的向量容器

  1
  2 #include <iostream>
  3 #include <vector>
  4
  5 using namespace std;
  6
  7 #define SIZE 10
  8
  9 int main()
 10 {
 11     vector<int> v(SIZE);
 12
 13     // for (int i = 0; i < SIZE; i++)
 14     // for (int i = 0; i < SIZE + 1; i++)
 15     for (int i = 0; i < SIZE + 2; i++)
 16         v[i] = i * i;
 17
 18     for (int i = 0; i < SIZE; i++)
 19         cout << v[i] << " ";
 20     cout << endl;
 21
 22     return 0;
 23 }

当我取消注释第(a)行时,一切都很好。

当我启用第(b)行时,我没有得到错误/恐慌。我猜这是因为向量类不进行绑定检查,并且代码在堆栈上写入内存不应该。正确?

然而,当我启用第(c)行时,我感到恐慌。当代码写入堆栈中的其他int时,为什么我会感到恐慌?但更奇怪的是,该回溯表明恐慌发生在第22行?我认为第16行应该发生恐慌。有人可以帮我理解。

(gdb) bt
#0  0x00007fd1494fe475 in *__GI_raise (sig=<optimized out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#1  0x00007fd1495016f0 in *__GI_abort () at abort.c:92
#2  0x00007fd14953952b in __libc_message (do_abort=<optimized out>, fmt=<optimized out>)
    at ../sysdeps/unix/sysv/linux/libc_fatal.c:189
#3  0x00007fd149542d76 in malloc_printerr (action=3, str=0x7fd14961b190 "free(): invalid next size (fast)",
    ptr=<optimized out>) at malloc.c:6283
#4  0x00007fd149547aac in *__GI___libc_free (mem=<optimized out>) at malloc.c:3738
#5  0x0000000000401098 in __gnu_cxx::new_allocator<int>::deallocate (this=0x7fff792fc320, __p=0x1370010)
    at /usr/include/c++/4.7/ext/new_allocator.h:100
#6  0x0000000000400fc2 in std::_Vector_base<int, std::allocator<int> >::_M_deallocate (this=0x7fff792fc320, __p=0x1370010,
    __n=10) at /usr/include/c++/4.7/bits/stl_vector.h:175
#7  0x0000000000400e3d in std::_Vector_base<int, std::allocator<int> >::~_Vector_base (this=0x7fff792fc320,
    __in_chrg=<optimized out>) at /usr/include/c++/4.7/bits/stl_vector.h:161
#8  0x0000000000400d28 in std::vector<int, std::allocator<int> >::~vector (this=0x7fff792fc320, __in_chrg=<optimized out>)
    at /usr/include/c++/4.7/bits/stl_vector.h:404
#9  0x0000000000400bbb in main () at ./main.cc:22

谢谢你, 艾哈迈德。

1 个答案:

答案 0 :(得分:2)

超出向量范围的写入会导致未定义的行为。什么事情都可能发生。在你的情况下,看起来像(c),你覆盖了一些内存分配器的簿记信息,当你的向量的析构函数试图在函数结束时释放内存时会导致崩溃。