Heap Corruption

Started by
1 comment, last by steviedisco 13 years, 5 months ago
Hi,

I've come across a problem that is currently holding me up and I am having difficulty tracking it down.

I am writing an opengl/directx render engine - am happy with my directx one so far and am getting my opengl one up to the same place with the intention of adding features to each at the same time.

I am however getting quite a simple problem that is holding me up.

I am getting a heap corruption error (using Visual Studio 2010) when I try to allocate a new array to a pointer. Like so,

In GLRenderEngine.h:

private:
...
GLubyte* _glIndices;
...

In GLRenderEngine.cpp

if (_glIndices)
delete[] _glIndices;

_glIndices = new GLubyte[indexCount];

I'm not a native C++ programmer so I'm flying by the seat of my pants a bit, but from what I've read heap corruptions occur whenever pointers are deleted incorrectly. With this in mind, I have put a breakpoint on every occurence of 'delete' in my code and up until this point (which is in initialisation of my little demo), no deletes have happened.

I do allocate a pointer to an array of GLfloats in the function beforehand, to represent a vertex buffer - that function works fine and the pointer to that has not been touched at this point.

Any ideas? I'll be eternally grateful :) gaaah
Advertisement
Heap corruption can also occur when writing past the end of an allocated block or before the beginning. The former is a lot more common than the latter and is probably the most common form of heap corruption. Heap consistency checks only occur when the heap is manipulated in some way which is why a lot of people believe that delete or free() causes heap corruption, but it's actually that the symptoms only show up when the delete or free() is called.

One tool for tracking this kind memory overrun on Windows is to use Application Verifier and set it to allocate a guard page after the end of every allocation.
Ha - that fixed it. I wasn't allocating enough room for the array in the function beforehand. I was only allocating vertexCount entries instead of vertexCount * 3

void GLRenderEngine::SetVertexBuffer(Vertex3D* vertices, int vertexCount)
{
if (_glVertices)
delete[] _glVertices;

_glVertices = new GLfloat[vertexCount * 3];

for (int i = 0; i < vertexCount; i++)
{
_glVertices[(i * 3)] = vertices._position.x;
_glVertices[(i * 3) + 1] = vertices._position.y;
_glVertices[(i * 3) + 2] = vertices._position.z;
}

glVertexPointer(3, GL_FLOAT, 0, _glVertices);
}

Thanks a lot :)

This topic is closed to new replies.

Advertisement