写入向量超过大小会导致恐慌 我有以下简单的C++程序,它使用STL < /P>的向量容器 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 } 1 2#包括 3#包括 4. 5使用名称空间标准; 6. 7#定义尺寸10 8. 9 int main() 10 { 11向量v(大小); 12 13//for(int i=0;i

写入向量超过大小会导致恐慌 我有以下简单的C++程序,它使用STL < /P>的向量容器 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 } 1 2#包括 3#包括 4. 5使用名称空间标准; 6. 7#定义尺寸10 8. 9 int main() 10 { 11向量v(大小); 12 13//for(int i=0;i,c++,stl,C++,Stl,写入超出向量边界会导致未定义的行为。任何情况都可能发生。在您的情况下,在case(c)中,您覆盖了内存分配器的某些簿记信息,这会在向量的析构函数试图在函数末尾释放内存时导致崩溃 (gdb) bt #0 0x00007fd1494fe475 in *__GI_raise (sig=<optimized out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64 #1 0x00007fd1495016f0 in *__GI_abort ()

写入超出向量边界会导致未定义的行为。任何情况都可能发生。在您的情况下,在case
(c)
中,您覆盖了内存分配器的某些簿记信息,这会在向量的析构函数试图在函数末尾释放内存时导致崩溃

(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