Sign in to follow this  
steviedisco

Heap Corruption

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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[i]._position.x;
_glVertices[(i * 3) + 1] = vertices[i]._position.y;
_glVertices[(i * 3) + 2] = vertices[i]._position.z;
}

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

Thanks a lot :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this