Bug in cutil.cpp memory leak

I think I have found a bug in cutil.cpp.

CUTBoolean CUTIL_API

cutSavePPM4ub( const char* file, unsigned char *data, 

			   unsigned int w, unsigned int h) 

{

	// strip 4th component

	int size = w * h;

	unsigned char *ndata = (unsigned char*) malloc( sizeof(unsigned char) * size*3);

	unsigned char *ptr = ndata;

	for(int i=0; i<size; i++) {

		*ptr++ = *data++;

		*ptr++ = *data++;

		*ptr++ = *data++;

		data++;

	}

	

	return savePPM( file, ndata, w, h, 3);;

}

Unless I’m using the function incorrectly, this implementation creates a memory leak. I am currently repeatedly calling CheckRender::savePPM, which calls cutSavePPM4ub, to save a series of images to make into a movie. If that is an incorrect approach, please let me know so I can do something better.

To resolve the memory leak, I added two lines to the end of the function.

CUTBoolean CUTIL_API

cutSavePPM4ub( const char* file, unsigned char *data, 

			   unsigned int w, unsigned int h) 

{

	// strip 4th component

	int size = w * h;

	unsigned char *ndata = (unsigned char*) malloc( sizeof(unsigned char) * size*3);

	unsigned char *ptr = ndata;

	for(int i=0; i<size; i++) {

		*ptr++ = *data++;

		*ptr++ = *data++;

		*ptr++ = *data++;

		data++;

	}

	

	CUTBoolean returner = savePPM( file, ndata, w, h, 3);

	free(ndata);

	return returner;

}

and this is another reason why you shouldn’t be using cutil.cpp–it is buggy, relatively untested, and not officially part of anything except SDK samples (and should not be used in your own projects, even those based on SDK apps).