FreeHGlobal Method
Collapse the table of content
Expand the table of content

Marshal.FreeHGlobal Method (IntPtr)


Frees memory previously allocated from the unmanaged memory of the process.

Namespace:   System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

public static void FreeHGlobal(
	IntPtr hglobal


Type: System.IntPtr

The handle returned by the original matching call to AllocHGlobal.

You can use FreeHGlobal to free any memory from the global heap allocated by AllocHGlobal, ReAllocHGlobal, or any equivalent unmanaged API method. If the hglobal parameter is IntPtr.Zero the method does nothing.

FreeHGlobal exposes the LocalFree function from Kernel32.DLL, which frees all bytes so that you can no longer use the memory pointed to by hglobal.

In addition to FreeHGlobal, the Marshal class provides two other memory-deallocation API methods: DestroyStructure and FreeCoTaskMem.


Passing an invalid handle value to FreeHGlobal causes an ArgumentException.

Legacy Code Example

The following example demonstrates calling the FreeHGlobal method. This code example is part of a larger example provided for the Marshal class.

// Demonstrate how to call GlobalAlloc and 
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal.AllocHGlobal(100);

The following example demonstrates how to convert the contents of a managed String class to unmanaged memory and then dispose of the unmanaged memory when done.

using System;
using System.Runtime.InteropServices;

class MainFunction
    static void Main()

    // Create a managed string.
    String  managedString = "I am a managed String";
    Console.WriteLine("1) managedString = " + managedString );

    // Marshal the managed string to unmanaged memory.
    IntPtr stringPointer = (IntPtr)Marshal.StringToHGlobalAnsi(managedString);
    Console.WriteLine("2) stringPointer = {0}", stringPointer );

    // Get the string back from unmanaged memory
    String RetrievedString = Marshal.PtrToStringAnsi( stringPointer);
    Console.WriteLine("3) Retrieved from unmanaged memory = " + RetrievedString );

    // Always free the unmanaged string.

    // IntPtr handle value is still the same:
    Console.WriteLine("4) stringPointer = " + stringPointer );

    // However, it contains no data after being freed:
    String RetrievedString2 = Marshal.PtrToStringAnsi( stringPointer);
    Console.WriteLine("5) RetrievedString2 = " + RetrievedString2 );

requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
© 2015 Microsoft