Skip to content

Safety of accessing freed GCHandle #46502

Answered by PathogenDavid
acaly asked this question in Q&A
Discussion options

You must be logged in to vote

I would like to know whether this is reliable, i.e., whether accessing the Target property of Freed handle is safe and always returns null.

It is not safe or reliable. Internally GCHandle is essentially an index into a table of references. When you free a handle, that entry of the table is deallocated and set to null.

When you're accessing Target of the dead handle, you're accessing that deallocated row of the table. If that row gets reused, it will no longer be null and will point to something else entirely.

You can observe this by allocating another handle immediately after freeing one:

using System;
using System.Runtime.InteropServices;

string a = "StringA";
string b = "StringB";
GC…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@acaly
Comment options

Answer selected by acaly
Comment options

You must be logged in to vote
1 reply
@acaly
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants