IntPtr 导致内存泄漏?

发布于 2024-10-31 06:00:57 字数 572 浏览 1 评论 0原文

这个函数是在一个循环中。当我运行程序时,IntPtr 行给了我内存问题,我已经添加了delete[],但它仍然没有解决内存问题,有人可以帮忙吗?谢谢

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;
} 

这是 C++\CLI

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥枳 2024-11-07 06:00:58

令人遗憾的是,这段代码能够编译,但这是设计使然的。应用于托管类型的删除运算符实际上不会释放任何内存。它对传递的对象调用 IDisposable::Dispose() 方法。令人遗憾的是,这甚至有效,IntPtr 被装箱以将其转换为对象,然后检查它是否实现 IDisposable 接口。当然不是,什么也没有发生。

您必须传递从 new 运算符返回的指针。不要忘记在finally 块中执行此操作,这样异常就不会导致泄漏。

顺便说一句,您评论的代码中有更多复杂性。您使用的 Bitmap 构造函数要求您保持 IntPtr 有效,直到不再使用 Bitmap 才能释放内存。所以使用delete实际上是无效的。考虑使用 Bitmap.LockBits() 来获取指向管理其自身内存的 Bitmap 的指针。并注意步幅。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文