Allocates memory from the local memory heap.
HLOCAL LocalAlloc(
UINT uFlags,
SIZE_T cbMem
);
LPTR: Allocates a shared, discardable memory object that is initialized to zero.LHND: Allocates a shared, discardable memory object.LMEM_FIXED: Allocates memory in the heap. The return value is a pointer to the allocated memory.LMEM_ZEROINIT: Initializes memory to zero.LMEM_DISCARDABLE: Discardable memory.cbMem is 0 and uFlags specifies a LMEM_MODIFY value, the function releases the memory pointed to by the handle returned by a previous call to the LocalAlloc function.
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.
Header: Declared in Windows.h
Library: Use Kernel32.lib
DLL: Kernel32.dll
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;
}