views:

104

answers:

3

For example I’ve got a third-party class with unsafe code in it’s methods. It makes some memory changes and doesn’t clear memory after itself. It happens, that i have to use this class and it’s unsafe methods. Can you, please, explain me, what will happen to those bytes written by unsafe code, after next Garbage Collector pass.

+2  A: 

The .NET Garbage Collector won't do anything with those bytes, as the runtime didn't allocate them. They'll just remain leaked.

Adam Robinson
A: 

Nothing happens. With unsafe code and memory allocation, its up to the unsafe code to correctly free system resources.

Alan
+4  A: 

The garbage collector won't touch them. On the one hand that's nice, because you don't have to worry about it interfering with unmanaged code. On the other hand, if you don't clean them up yourself it's a memory leak.

Anytime you use unsafe code that allocates memory I would wrap it in an object that implements IDisposable. If a third-party class doesn't already implement IDisposable I would create a new class that does to encapsulate the functionality.

Joel Coehoorn