This documentation is archived and is not being maintained.

Marshal.FreeHGlobal Method

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

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

public static void FreeHGlobal (
	IntPtr hglobal
)
public static void FreeHGlobal (
	IntPtr hglobal
)
public static function FreeHGlobal (
	hglobal : IntPtr
)

Parameters

hglobal

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 a null reference (Nothing in Visual Basic), 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. For additional information about LocalFree, see the MSDN Library.

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

NoteNote

This method uses SecurityAction.LinkDemand to prevent it from being called from untrusted code; only the immediate caller is required to have SecurityPermissionAttribute.UnmanagedCode permission. If your code can be called from partially trusted code, do not pass user input to Marshal class methods without validation. For important limitations on using the LinkDemand member, see Demand vs. LinkDemand.

Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition Platform Note: Passing an invalid handle value to FreeHGlobal causes an ArgumentException.

The following code 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);
Marshal.FreeHGlobal(hglobal);

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

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0
Show: