Memory Management

Core APIs for managing application memory space.

This section details the Windows API functions used for allocating, managing, and querying memory within your applications. Efficient memory management is crucial for application performance, stability, and resource utilization.

Key Concepts

Understanding the following concepts is fundamental to effective memory management on Windows:

Core Memory Management Functions

VirtualAlloc
LPVOID VirtualAlloc( LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect );
Parameters:
  • lpAddress: The starting address of the region to allocate.
  • dwSize: The size of the region to allocate, in bytes.
  • flAllocationType: The type of memory allocation (e.g., MEM_COMMIT, MEM_RESERVE).
  • flProtect: The memory protection for the region (e.g., PAGE_READWRITE, PAGE_EXECUTE_READ).
Return Value: The starting address of the allocated region, or NULL if the function fails.
Remarks: Allocates, commits, or reserves a region of memory pages in the virtual address space of the calling process. This is a low-level function for granular memory control.
VirtualFree
BOOL VirtualFree( LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType );
Parameters:
  • lpAddress: The starting address of the region of pages to be freed.
  • dwSize: The size of the region, in bytes.
  • dwFreeType: The type of operation (e.g., MEM_RELEASE, MEM_DECOMMIT).
Return Value: TRUE if the function succeeds, FALSE otherwise.
Remarks: Decommits or releases a region of pages within the virtual address space of the calling process.
See Also:
HeapAlloc
LPVOID HeapAlloc( HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes );
Parameters:
  • hHeap: A handle to the heap.
  • dwFlags: Allocation options (e.g., HEAP_ZERO_MEMORY).
  • dwBytes: The number of bytes to allocate.
Return Value: A pointer to the allocated memory, or NULL if the function fails.
Remarks: Allocates a block of memory from a specified heap. This function is typically used with heaps created by HeapCreate.
See Also:

Advanced Memory Operations

Memory Protection Flags

When allocating or modifying memory regions with functions like VirtualAlloc, you specify protection flags to control access. Common flags include:

Memory-Mapped Files

Memory-mapped files provide an efficient way to access file contents directly in memory. Key functions include:

Best Practices

For more detailed information and comprehensive examples, please refer to the official Microsoft Learn documentation.