-4
我有使用矢量容器從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),所有的好下面的簡單的C++程序。
當我啓用行(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
謝謝 Ahmed。