内存访问冲突
mem access violation
我想知道这段代码是如何违反内存访问的?
{
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
相同的数组,然后您尝试将该内存与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
指向的内存后再次尝试使用它时,您正在调用未定义的行为,在这种情况下,它会给您内存访问冲突。
相关文章:
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++中的内存分配(引发异常:读取访问冲突)
- 在尝试使用CUDA分配内存时,我遇到了访问冲突写入位置错误
- 使用加速进程间创建消息队列 - 内存访问冲突
- C 指针转换会导致内存访问冲突
- 为什么创建进程 API 调用会导致内存访问冲突?
- 访问共享内存时出现读取访问冲突
- Python C++扩展 - 内存泄漏或访问冲突
- 如何修复<程序名称>中的"<内存位置>未处理的异常。Visual Studio 2017 中的访问冲突写入位置<内存位置>"
- 使用 std::map 作为本地成员的内存访问冲突
- 编译哈希算法时出现内存访问冲突错误
- 使用内存访问冲突错误
- 堆栈引发内存访问冲突
- 使用 Boost::序列化时内存访问冲突
- 调用std::vector::empty()时内存访问冲突读取位置
- 简单加密程序集程序-写入内存位置时发生访问冲突
- 动态分配内存时发生访问冲突
- 基于 SAPI 的应用程序在枚举令牌时引发内存访问冲突
- 内存访问冲突
- 访问冲突写入位置0x00000000.内存集函数问题