LocalAlloc Function

Allocates memory from the local memory heap.

Syntax


HLOCAL LocalAlloc(
  UINT  uFlags,
  SIZE_T cbMem
);
            

Parameters

Return Value

If the function succeeds, the return value is a handle to the newly allocated memory object. The handle is a unique value used to access the memory object. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Requirements

Header: Declared in Windows.h

Library: Use Kernel32.lib

DLL: Kernel32.dll

See Also

Example

The following code example demonstrates how to allocate a block of memory and initialize it to zero.


#include <windows.h>
#include <stdio.h>

int main() {
    HLOCAL hMem;
    LPVOID lpMem;
    SIZE_T size = 1024; // Allocate 1 KB

    // Allocate memory and initialize to zero
    hMem = LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, size);

    if (hMem == NULL) {
        fprintf(stderr, "LocalAlloc failed with error: %lu\n", GetLastError());
        return 1;
    }

    lpMem = LocalLock(hMem); // Lock the memory to get a pointer
    if (lpMem == NULL) {
        fprintf(stderr, "LocalLock failed with error: %lu\n", GetLastError());
        LocalFree(hMem); // Clean up if lock fails
        return 1;
    }

    printf("Successfully allocated %zu bytes of memory.\n", size);

    // You can now use lpMem to access the allocated memory

    LocalUnlock(hMem); // Unlock the memory
    LocalFree(hMem);   // Free the allocated memory

    return 0;
}