3

This function is in a loop. When I run the program, the line with IntPtr is giving me memory problems, I've put delete[], but it still doesn't solve the memory problem, can anyone help please? thanks

void showImage(IplImage *img,System::Windows::Forms::PictureBox^ picturebox)
{

IntPtr ip(new unsigned char[img->widthStep*img->height]); // this line causing memory usage to keep going up very fast

//memcpy(ip.ToPointer(),img->imageData,img->widthStep*img->height);

//picturebox->Image = gcnew Bitmap(img->width,img->height, img->widthStep, System:rawing::Imaging::PixelFormat::Format24bppRgb, ip);

delete[] ip;
} 

This is C++\CLI

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Qmage
  • 289
  • 4
  • 13

1 Answers1

2

It is rather sad that this code compiles, but that is by design. The delete operator applied to a managed type doesn't actually free any memory. It calls the IDisposable::Dispose() method on the passed object. It is rather sad that this even works, the IntPtr gets boxed to turn it into an object and then checked to see if it implements the IDisposable interface. It doesn't of course, nothing happens.

You have to pass the pointer that you got back from the new operator. Don't forget to do this in a finally block so an exception cannot cause a leak.

Btw, there are more complications in the code that you commented. The Bitmap constructor you use requires you to keep the IntPtr valid, you cannot release the memory until the Bitmap is no longer used. So using delete isn't actually valid. Consider using Bitmap.LockBits() instead to get a pointer to a Bitmap that manages its own memory. And watch out for stride.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • how do I pass the pointer that I got back from the new operator? can you show some snippet, thanks alot – Qmage Apr 09 '11 at 20:04
  • Martinho already showed you. Pay attention to the paragraph I added. – Hans Passant Apr 09 '11 at 20:05
  • Ya, like you said, after changed to the code Martinho suggested, the memory problem is solved, but instead my picturebox could not load properly. – Qmage Apr 09 '11 at 20:10
  • lockbits? can you show a snippet with LockBits(), I don't really get your last 2 sentence – Qmage Apr 09 '11 at 20:11
  • There's a good example in the MSDN Library. We just hand you the proper caliber bullets here. Pointing the gun at your foot is your job. – Hans Passant Apr 09 '11 at 20:13
  • ok I will look it up, thanks alot Hans, and Martinho as well, I would rate your answers up, but i need 15 reps, so thanks again! :) – Qmage Apr 09 '11 at 20:15