简体   繁体   English

此IntPtr是否指向已分配的非托管内存?

[英]Is this IntPtr pointing to allocated unmanaged memory or not?

First, I allocate memory and get the pointer: 首先,我分配内存并获取指针:

IntPtr pointer = Marshal.AllocHGlobal(size);

Then, I try to release the memory pointed by my pointer: 然后,我尝试释放指针指向的内存:

Marshal.FreeHGlobal(pointer);

But in my application it raises sometimes a fatal unknown exception with just this explaination: "a memory fragment has been damaged". 但是在我的应用程序中,有时仅给出以下解释就会引发致命的未知异常:“内存碎片已损坏”。 I guess this is because I try to free a pointer that points to a memory block already disallocated by freeing another pointer... 我猜这是因为我试图通过释放另一个指针来释放一个指向已分配的内存块的指针...

My question is: using the IntPtr pointer, is there any way to check if the memory block is still allocated or has been already disallocated ? 我的问题是:使用IntPtr指针,是否有任何方法可以检查内存块是否仍在分配或已经被分配?

释放指针的好方法是Marshal.FreeHGlobal(),因此,如果取消分配指针,这是一个逻辑问题,但是您可以在try / catch中完成它,因此如果遇到catch异常,则已经分配了指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM