【发布时间】:2020-12-28 11:53:14
【问题描述】:
我需要帮助弄清楚为什么这段代码会引发读取访问冲突
代码在数组的第 4 个值处引发读取访问冲突,这在我在第 7 行和第 8 行添加动态内存分配时开始发生
ProceduralStories.cpp
#include <iostream>
#include "ProceduralStories.h"
void main()
{
Object* _objects = NULL;
_objects = new Object[10];
for (int i = 0; i < 10; i++)
{
Object object = Object
{
object.position = glm::vec3 {rand() % 1000 + 1, rand() % 1000 + 1, rand() % 1000 + 1},
object.mesh = i
};
_objects[i] = object;
}
Location location1
{
location1.position = glm::vec3 {0.0f, 0.0f, 0.0f},
};
for (int i = 0; i < 10; i++)
{
location1.objects[i] = _objects[i]; //Throws a Read Access Violation at the 4th value of the array, so [3]
std::cout << location1.objects[i].mesh << ", (" << location1.objects[i].position.x << ',' << location1.objects[i].position.y << ',' << location1.objects[i].position.z << ')' << std::endl;
}
}
ProceduralStories.h
#include "glm/vec3.hpp"
struct Object
{
glm::vec3 position;
int mesh;
};
struct Location
{
glm::vec3 position;
Object objects[];
};
【问题讨论】:
-
location1 在第 21 行的构造中没有为对象分配空间。正如大卫在他的回答中所说。你也有内存泄漏。 _objects 是新的,但从未被删除。
标签: c++ arrays memory-management