c++ - 内存访问冲突

标签 c++

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

{
   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[] a时,b仍然指向与a相同的数组,然后你尝试使用那 block 内存使用 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/

相关文章:

c# - 从 C# 调用 C++ 函数传递类型剥离的空指针

c# - Assembly.LoadFrom 在包含 MFC 的 cpp/CLI DLL 上失败

c++ - 使用 fscanf 了解循环

c++ - 来自模板类的多重继承

C++ Typedef 和运算符重载

c++ - SSE2 整数溢出检查

C++ stat(const char *d_name) 总是返回 -1

c++ - 作为类成员的常量引用

c++ - C函数可变大小的堆栈数组获取常量

c++ - vector<int>() vs vector<int>{} vs NULL vs size=0 有什么区别?