为什么此代码会生成错误:堆已损坏

时间:2016-01-07 05:05:22

标签: c++ visual-studio

使用visual studio 2013,我一直试图运行下面的代码,但不知怎的,我得到了一个" Heap已经损坏了#34;变量vertexPointer到达数字7172时的异常。 有时我会收到错误:" igdusc32.pdb未加载"

请帮帮我!!

#define VERTEX_COUNT 128
#define TERRAIN_SIZE 800

int count = VERTEX_COUNT * VERTEX_COUNT;
    int size3 = count * 3;
    int size2 = count * 2;
    float* vertices = (float*)malloc(size3);
    float* normals = (float*)malloc(size3);
    float* uvs = (float*)malloc(size2);

int vertexPointer = 0;

for (int i = 0; i<VERTEX_COUNT; i++){
    for (int j = 0; j<VERTEX_COUNT; j++){

        vertices[vertexPointer*3] = (float)j / ((float)VERTEX_COUNT - 1) * TERRAIN_SIZE;
        vertices[(vertexPointer * 3) +1] = 0.0f;
        vertices[(vertexPointer * 3) + 2] = (float)i / ((float)VERTEX_COUNT - 1) * TERRAIN_SIZE;

        normals[vertexPointer * 3] = 0.0;
        normals[(vertexPointer * 3) +1] = 1.0f;
        normals[(vertexPointer * 3) + 2] = 0.0f;

        uvs[vertexPointer * 2] = (float)j / ((float)VERTEX_COUNT - 1);
        uvs[(vertexPointer * 2)+1] = (float)i / ((float)VERTEX_COUNT - 1);

        vertexPointer++;
    }
}

1 个答案:

答案 0 :(得分:3)

您正在分配,例如verticessize3 字节,但您需要分配size3 浮点数。所以改为:

float* vertices = (float*)malloc(size3 * sizeof(float));
float* normals = (float*)malloc(size3 * sizeof(float));
float* uvs = (float*)malloc(size2 * sizeof(float));

或者,这是C ++,改为使用new

auto vertices = new float[size3];
auto normals = new float[size3];
auto uvs = new float[size2];

(然后你的清理工作必须改为delete[] vertices等)。

您还可以使用std::vector<float>,这是更优选的。

std::vector<float> vertices(size3);
std::vector<float> normals(size3);
std::vector<float> uvs(size2);