我有以下使用 STL 中的矢量容器的简单 C++ 程序
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
谢谢你,艾哈迈德。