内存访问冲突

mem access violation

本文关键字:访问冲突 内存      更新时间:2023-10-16

我想知道这段代码是如何违反内存访问的?

{
   Vector3f *a = new Vector3f [10];
   Vector3f *b = a;
   b[9] = Vector3f (2,3,4);
   delete[] a;
   a = new Vector3f [10];
   b[4] = Vector3f (1,2,3);
   delete[] a;
}
因为当您

调用delete[] ab仍然指向与a相同的数组,然后您尝试将该内存与b[4]一起使用。

Vector3f *a = new Vector3f [10]; // a initialised to a memory block x
Vector3f *b = a;                 // b initialised to point to x also
b[9] = Vector3f (2,3,4);         // x[9] is assigned a new vector
delete[] a;                      // x is deallocated
a = new Vector3f [10];           // a is assigned a new memory block y
b[4] = Vector3f (1,2,3);         // x is used (b still points to x)
                                 // x was deallocated and this causes segfault
delete[] a;                      // y is deallocated
它这一

行:

b[4] = Vector3f (1,2,3);

b仍然指向旧的、自由的a.

b指向第一个删除的a(即 b 不指向新分配a),因此当您在删除b指向的内存后再次尝试使用它时,您正在调用未定义的行为,在这种情况下,它会给您内存访问冲突。