After I call event() several thousand times, I run out of memory. I think it's because I'm using the new operator in the method without a corresponding delete |
You are correct. That's exactly what's happening.
For every new, you should have a matching delete. It doesn't
have to be in the same function, it just is generally easier that way.
You have two options here.
Option 1: groupLines new's an ImageReader and returns it. The calling function is responsible for deleting it.
Option 2: groupLines has an ImageReader passed to it by pointer, rather than newing it itself.
Either one will work in your case. Probably Option 1 would be better if the size of the output image is not fixed. If it is fixed, then option 2 is probably better. But it's just a style thing so pick whichever you like.
Option 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
void event(){
ImageReader im = new ImageReader(1024,1024);
ImageReader newIm = groupLines(im);
// use 'im' and 'newIm' here
// when you're done with them:
delete im;
delete newIm;
}
ImageReader * groupLines(ImageReader * im){
ImageReader* dummy = new ImageReader( ... );
// modify 'dummy' here
return dummy;
}
|
Notice that we don't new 'newIm' in event(). It is new'd by groupLines.
Option 2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void event(){
ImageReader im = new ImageReader(1024,1024);
ImageReader newIm = new ImageReader(1024,256);
groupLines(im,newIm);
// use 'im' and 'newIm' here
// when you're done with them:
delete im;
delete newIm;
}
void groupLines(ImageReader * im, ImageReader * dummy){
// modify 'dummy' here
}
|
In option 2, note that we don't new dummy in groupLines. Instead we just use it as passed. It is new'd by event().