开发者

Freeing a pointer from memory in c#

开发者 https://www.devze.com 2023-03-11 13:18 出处:网络
I\'m dealing with pointer in C# using fixed{} phrases. I placed my code inside the brackets of the fixed statement and want to know if the Garbage collection will handle the pointer freeing after the

I'm dealing with pointer in C# using fixed{} phrases.

I placed my code inside the brackets of the fixed statement and want to know if the Garbage collection will handle the pointer freeing after the fixed sta开发者_StackOverflowtement

fixed{int * p=&x}
{
// i work with x.
}

if not how can I free it?


Your pointer points to a managed object (x) so there is nothing to worry about: the pointer does not need to be freed (or rather, it goes out of scope at the end of the fixed block) and the pointee x itself is managed by the GC.


Some similar code in C will things make more clear:

{
   int x;     // allocates space for x

   {
     int *p=&x; // does not allocate for something p points to (only for p)

     // ...
   } // leaves inner scope, p vanishes, *p is not deallocated
   // ...
} // leaves outer scope, x is deallocated

The C# code does essentially the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消