× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Is memory cleared before garbage collection?

John Feminella
Feb 02, 2015
<p>Practically speaking, no, this doesn't happen. Overwriting memory you've just freed takes time, so there are performance penalties. "Secure" objects like <a href="http://msdn.microsoft.com/en-us/library/System.Security.SecureString%28v=vs.110%29.aspx" rel="nofollow">SecureString</a> are <a href="http://msdn.microsoft.com/en-us/library/system.security.securestring.clear%28v=vs.110%29.aspx" rel="nofollow">just wiping themselves</a>, not relying on the GC.</p> <p>More broadly, it depends very much on that particular implementation of that particular language. Every language that assumes the existence of a GC (like C#) specifies different rules about how and when garbage collection should happen.</p> <p>To take your C# example, the C# specification does not require that objects be overwritten after being freed, and it doesn't forbid it either:</p> <blockquote> <p>Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object.</p> <p>§3.9 <a href="http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.docx" rel="nofollow">C# 5.0 Language Specification</a></p> </blockquote> <p>If the memory is later assigned to a reference type, you'll have a constructor that does your own custom initialization. If the memory is later assigned to a value type, it gets zeroed out before you can start reading from it:</p> <blockquote> <p>Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference.</p> <p>§5.2 <a href="http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.docx" rel="nofollow">C# 5.0 Language Specification</a></p> </blockquote> <p>Additionally, there's at least two implementations of C# -- Microsoft's implementation and Mono's implementation, so just saying "C#" isn't specific enough. Each implementation might decide to overwrite memory (or not).</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23087071/Is%20memory%20cleared%20before%20garbage%20collection?/23087417">Stack Overflow</a>.</p>
comments powered by Disqus