Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

LocalAlloc (kernel32)
 
.
Summary
Allocates the specified number of bytes from the heap.

C# Signature:

[DllImport("kernel32.dll")]
static extern IntPtr LocalAlloc(uint uFlags, UIntPtr uBytes);

User-Defined Types:

The uFlags parameter above can also be represented by a value from the LocalMemoryFlags enumeration described below:

[Flags]
public enum LocalMemoryFlags {
    LMEM_FIXED = 0x0000,
    LMEM_MOVEABLE = 0x0002,
    LMEM_NOCOMPACT = 0x0010,
    LMEM_NODISCARD = 0x0020,
    LMEM_ZEROINIT = 0x0040,
    LMEM_MODIFY = 0x0080,
    LMEM_DISCARDABLE = 0x0F00,
    LMEM_VALID_FLAGS = 0x0F72,
    LMEM_INVALID_HANDLE = 0x8000,
    LHND = (LMEM_MOVEABLE | LMEM_ZEROINIT),
    LPTR = (LMEM_FIXED | LMEM_ZEROINIT),
    NONZEROLHND = (LMEM_MOVEABLE),
    NONZEROLPTR = (LMEM_FIXED)
}

Notes:

By default, the allocated memory is not zeroed. Use the LMEM_ZEROINT flag to zero the memory.

If a zero pointer is returned, the system is out of memory and you should throw an OutOfMemoryException.

Once allocated, use the LocalFree function to free memory allocated with this function. If you do not do this, you have created a memory leak.

Tips & Tricks:

Please add some!

Sample Code:

The following method wraps LocalAlloc in order to allocate a zeroed memory block of the specified size:

public IntPtr Alloc(int size) {
    // Allocate the memory, zeroing it in the progress
    IntPtr memPtr = LocalAlloc(LocalMemoryFlags.LPTR, new UIntPtr((uint)size));
    // Throw an OutOfMemoryException if out of memory
    if (memPtr == IntPtr.Zero)
        throw new OutOfMemoryException();
    return memPtr;
}

Note that this sample uses the LocalMemoryFlags enumeration listed above.

Alternative Managed API:

System.Runtime.InteropServices.Marshal.AllocHGlobal

Documentation
LocalAlloc on MSDN

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions