LocalAlloc (kernel32)
Last changed: -121.102.64.14

.
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