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

Writing to vector beyond size causes panic

本文关键字:      更新时间:2023-10-16

我有以下简单的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

谢谢艾哈迈德。

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

相关文章:
  • 没有找到相关文章