0

我想知道这段代码是如何产生内存访问冲突的?

{
   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;
}
4

3 回答 3

5

因为仍然指向与调用时b相同的数组,然后您尝试将该内存与.adelete[] ab[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
于 2012-05-13T20:19:18.433 回答
3

这行:

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

b依然指着旧的,解脱了a

于 2012-05-13T20:19:32.517 回答
3

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

于 2012-05-13T20:19:48.833 回答