Allocates memory from the local memory heap.
LPVOID LocalAlloc(
UINT uFlags,
SIZE_T uBytes
);
| Parameter | Description |
|---|---|
uFlags |
The allocation type. This parameter can be one of the following values:
LMEM_FIXED or LMEM_MOVEABLE with LMEM_ZEROINIT.
|
uBytes |
The number of bytes of memory to allocate. If uFlags is LMEM_FIXED, this parameter is the size of the memory block. If uFlags is LMEM_MOVEABLE, this parameter is the size of the memory block in bytes.
|
uFlags is LMEM_FIXED, the return value is a pointer to the allocated memory.
NULL. The extended error information is available in the GetLastError function.
Applications running on Windows use the system's global heap for all memory allocations. The LocalAlloc, LocalReAlloc, and LocalFree functions manage the local heap, and the GlobalAlloc, GlobalReAlloc, and GlobalFree functions manage the global heap.
For greater efficiency, use the HeapAlloc function with a handle to the process's memory heap, which is returned by the GetProcessHeap function.
When you no longer need memory allocated by LocalAlloc, you must free it by calling the LocalFree function.
#include <windows.h>
#include <stdio.h>
int main() {
LPVOID lpMem = NULL;
HANDLE hMem = NULL;
SIZE_T size = 100; // Allocate 100 bytes
// Allocate movable memory, initialized to zero
hMem = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, size);
if (hMem == NULL) {
fprintf(stderr, "LocalAlloc failed with error: %lu\n", GetLastError());
return 1;
}
printf("Successfully allocated memory handle: %p\n", hMem);
// Lock the memory to get a pointer
lpMem = LocalLock(hMem);
if (lpMem == NULL) {
fprintf(stderr, "LocalLock failed with error: %lu\n", GetLastError());
LocalFree(hMem); // Clean up
return 1;
}
printf("Memory pointer: %p\n", lpMem);
// Use the memory here...
char* data = (char*)lpMem;
strcpy(data, "Hello, Windows API!");
printf("Data in memory: %s\n", (char*)lpMem);
// Unlock the memory
LocalUnlock(hMem);
// Free the memory
LocalFree(hMem);
printf("Memory freed.\n");
return 0;
}