Freeing a pointer from memory in c#
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.
精彩评论