我想知道这段代码是如何产生内存访问冲突的?
{
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;
}
我想知道这段代码是如何产生内存访问冲突的?
{
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;
}
因为仍然指向与调用时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
这行:
b[4] = Vector3f (1,2,3);
b
依然指着旧的,解脱了a
。
b
指向第一个删除的a
(即b
不指向新分配 a
的),因此当您b
在删除它指向的内存后尝试再次使用时,您正在调用未定义的行为,在这种情况下,它会给您一个内存访问冲突。