我想知道这段代码如何导致内存访问冲突?

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

最佳答案

因为在调用ba仍指向与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

关于c++ - 内存访问冲突,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10574892/

10-16 03:41