Help with memory leak (malloc)
I'v followed a tutorial to use OGL tesselaton. In one of the callbacks there is a malloc and it creates a leak every time I render a new frame.
void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4],
GLfloat weight[4], GLdouble **dataOut)
{
GLdouble *vertex;
vertex = (GLdouble *) malloc(6 * sizeof(GLdouble));
vertex[0] = coords[0];
vertex[1] = coords[1];
vertex[2] = coords[2];
for (int i = 3; i < 6; i++)
{
vertex[i] = weight[0] * vertex_data[0][i] +
weight[1] * vertex_data[0][i开发者_高级运维] +
weight[2] * vertex_data[0][i] +
weight[3] * vertex_data[0][i];
}
*dataOut = vertex;
}
I'v tried to free(vertex) but then the polygons did not render. I also tried allocating on the heap then doing delete(vertex) but then the polygon rendered awkwardly. I'm not sure what to do.
Thanks
You should call free
on whatever dataOut
points to. For example, if you did this from the calling function:
combineCallback (coords, vertex_data, weight, &dataOut);
then you should call free (dataOut)
after you're done using it later. If you free (vertex)
, that effectively means whatever dataOut
points to is free to be overwritten because you assigned the address of vertex
to *dataOut
. In other words, don't free vertex
; free whatever dataOut
points to.
The tool you want to look at is called valgrind, at http://valgrind.org/. That's assuming you're running on a Linux system.
As a note to readers, the "-grind" in valgrind is not related to the English word "grind".
The "Val" as in the world "value". The "grind" is pronounced with a short 'i' -- ie. "grinned" (rhymes with "tinned") rather than "grined" (rhymes with "find").
You can't free the vertex because you are assigning the memory to the dataOut object. You need to free the dataOut object once you are done with it.
I'm not sure how to fix your memory leak situation, however, one thing I would point out, is that using "delete" (I assume you meant the c++ 'delete' operator) to clean up memory that was allocated with "malloc", is highly discouraged.
Generally speaking, you need to stick with the appropriate functions for what you used to allocate in the first place. In C++ you would use 'delete' after allocating memory with 'new', and in C you would use 'free' after allocating memory with 'malloc'.
According to the docs for GLUT_TESS_COMBINE,
The user is responsible for freeing the memory some time after gluTessEndPolygon is called.
One way is to add the memory you allocate to a linked list and free it all when you're done.
You need to free the data somewhere outside this function, after you're finished using it. Without seeing the other code, it's a bit hard to guess where that will be though. You might be better off allocating the data elsewhere, and passing a pointer to it in so this can modify that other data. This is particularly true when you're likely to generate quite a bit of data (it can avoid allocating and freeing a lot of data).
精彩评论