我想知道这段代码是如何导致内存访问冲突的?
{
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;
}
答案 0 :(得分:5)
当您致电b
时,a
仍指向与delete[] 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
答案 1 :(得分:3)
这一行:
b[4] = Vector3f (1,2,3);
b
仍然指向旧的a
。
答案 2 :(得分:3)
b
指向首先删除的a
(即b
未指向新分配的 a
),所以当你删除它指向的内存后再次尝试使用b
,你正在调用未定义的行为,在这种情况下,它会给你一个内存访问冲突。