delete []导致程序崩溃

时间:2014-11-09 15:20:23

标签: c++

我创建一个大小为" N"的数组,然后通过数组循环N次并设置数组的值,当我完成使用它时,我试图删除[]它。然后我的程序崩溃,我100%确定我没有使用任何堆栈。

代码:

vec3 positions[numVertices];
vec2 textureCoords[numVertices];

for(unsigned int timesLooped = 0; timesLooped < numVertices; timesLooped++)
{
    positions[timesLooped] = vertices[timesLooped].getPosition();
    textureCoords[timesLooped] = textureCoords[timesLooped].getTextureCoord();
}

// Vertex position buffer.
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject[POSITION_VB]);
glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(positions[0]), positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

// Vertex texture coordinates buffer.
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject[POSITION_TB]);
glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(textureCoords[0]), textureCoords, GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);

delete[] positions; // CRASHES
delete[] textureCoords; // CRASHES

我不知道它崩溃的原因,但我只是使用了矢量:

vector<vec3> positions;
vector<vec2> textureCoords;

positions.reserve(numVertices);
textureCoords.reserve(numVertices);

for(unsigned int timesLooped = 0; timesLooped < numVertices; timesLooped++)
{
    positions.push_back(vertices[timesLooped].getPosition());
    textureCoords.push_back(vertices[timesLooped].getTextureCoord());
}

// Vertex position buffer.
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject[POSITION_VB]);
glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(positions[0]), &positions[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

// Vertex texture coordinates buffer.
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject[POSITION_TB]);
glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(textureCoords[0]), &textureCoords[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);

2 个答案:

答案 0 :(得分:2)

positionstexturecoordinates在堆栈中。 delete命令用于释放分配有new的内存,即堆上的变量。

堆栈:

{
   vec3 positions[numVertices]; //<--created on stack here


} <--- positions automatically freed at end of scope

堆:

{
  vec3* positions = new vec3[numVertices]; //<--created on heap here


  delete [] positions; //<-- only freed when delete [] called

}<-- not freed at end of scope, would have memory leak without delete [] call

参见例如Calling delete on variable allocated on the stack

答案 1 :(得分:1)

您在堆栈上定义数组并尝试使用delete[]释放该内存,这是非法的。您只能使用delete[]分配的new[]内存。