I’ve implemented Bill Dudney’s .Obj model loader in an OpenGL project of mine and am currently having massive memory leaks!
Using instruments, I’ve managed to narrow it down to the function below. And I think it’s something to do with ptr never being freed, but I still need to return ptr at the end of the function.
const void * TextureCoordBytes(CFAllocatorRef allocator, const void *value, GLuint *size)
{
// extract the count
GLuint count = ((GLuint *)value)[0];
void *ptr = NULL;
if(1 == count)
{ // a 1D texture
ptr = CFAllocatorAllocate(allocator, sizeof(GLfloat), 0);
((GLfloat*)ptr)[0] = ((TextureCoord1D *)value)->u;
*size = sizeof(GLfloat);
}
else if(2 == count)
{ // a 2D texture
ptr = CFAllocatorAllocate(allocator, 2 * sizeof(GLfloat), 0);
((GLfloat*)ptr)[0] = ((TextureCoord2D *)value)->u;
((GLfloat*)ptr)[1] = ((TextureCoord2D *)value)->v;
*size = 2 * sizeof(GLfloat);
}
else if(3 == count)
{ // a 3D texture
ptr = CFAllocatorAllocate(allocator, 3 * sizeof(GLfloat), 0);
((GLfloat*)ptr)[0] = ((TextureCoord3D *)value)->u;
((GLfloat*)ptr)[1] = ((TextureCoord3D *)value)->v;
((GLfloat*)ptr)[2] = ((TextureCoord3D *)value)->w;
*size = 3 * sizeof(GLfloat);
}
return ptr;
}
Does anybody know of something I’m missing here or of a way I can use free(ptr); and still return ptr; after it?
You have to first return ptr, use the allocated data, than free it. The consumer of returned ptr-s should handle freeing when no longer needed or at app exit.