Skip to main content
Be Bitwise

Memory Management APIs

The Windows API (Win32) Fundamentals · Windows Programming track

10 min read

In this module

Controlling Memory at the Page Level

The Win32 memory management APIs give you direct control over virtual memory at page granularity. Where malloc/free operate on a heap, VirtualAlloc/VirtualFree work directly on the process's virtual address space — reserving ranges and committing storage to back them. You need this for memory-efficient applications, custom allocators, JIT compilers, and understanding how memory exploits actually work.

VirtualAlloc: The Foundation

VirtualAlloc is the primary API for allocating virtual memory:

c
LPVOID VirtualAlloc(
LPVOID lpAddress, // Desired address (NULL = system chooses)
SIZE_T dwSize, // Size in bytes (rounded up to page size)
DWORD flAllocationType, // MEM_RESERVE, MEM_COMMIT, or both
DWORD flProtect // PAGE_READWRITE, PAGE_EXECUTE_READ, etc.
);

The Two-Phase Model: Reserve then Commit

Windows separates reserving address space from committing storage to back it:

c
// Phase 1: Reserve a large address range (no physical memory used)
LPVOID base = VirtualAlloc(
NULL, // System chooses address
1024 * 1024 * 1024, // Reserve 1 GB of address space
MEM_RESERVE, // Reserve only - no physical pages
PAGE_NOACCESS // No access until committed
);
// At this point: 1 GB of virtual address space is reserved
// Physical memory used: 0 bytes (the kernel just records the range
// in a VAD, a virtual address descriptor; no page table entries yet)
// Phase 2: Commit pages as needed (charges them against the commit limit)
LPVOID page = VirtualAlloc(
base, // Within the reserved range
4096, // Commit one page (4 KB)
MEM_COMMIT, // Commit storage (RAM + pagefile)
PAGE_READWRITE // Read/write access
);
// This 4 KB page is now guaranteed backing in RAM or the pagefile,
// but a physical page is only assigned when it's first touched
// Commit more pages later as the data structure grows
LPVOID nextPage = VirtualAlloc(
(BYTE*)base + 4096, // Next page in the range
4096,
MEM_COMMIT,
PAGE_READWRITE
);

This two-phase model is ideal for data structures that may grow large but start small, like stacks, hash tables, or dynamic arrays:

text
Reserved region (1 GB):
┌──────────┬──────────┬──────────────────────────────────────┐
│ Committed│ Committed│ Reserved but not committed │
│ (4 KB) │ (4 KB) │ (no physical memory) │
│ RW │ RW │ PAGE_NOACCESS │
└──────────┴──────────┴──────────────────────────────────────┘
▲ base ▲ base+4K ▲ base+8K ▲ base+1GB
Allocation Granularity

VirtualAlloc aligns reservation base addresses to the allocation granularity (64 KB on x86/x64). Committed page sizes align to the page size (4 KB). This means reserving 1 byte reserves 64 KB of address space, and committing 1 byte commits a whole 4 KB page. The 64 KB granularity prevents excessive fragmentation of the address space.

One-Step Allocation

For simple cases, you can reserve and commit simultaneously:

c
LPVOID mem = VirtualAlloc(
NULL,
65536, // 64 KB
MEM_RESERVE | MEM_COMMIT, // Both at once
PAGE_READWRITE
);
// Ready to use immediately
memset(mem, 0, 65536); // All committed pages are zero-initialized

VirtualProtect: Changing Page Permissions

You can change the protection of committed pages at any time:

c
// Allocate read/write memory
LPVOID code = VirtualAlloc(NULL, 4096,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
// Write machine code into it
unsigned char shellcode[] = {
0xB8, 0x2A, 0x00, 0x00, 0x00, // mov eax, 42
0xC3 // ret
};
memcpy(code, shellcode, sizeof(shellcode));
// Change to executable (and remove write permission)
DWORD oldProtect;
VirtualProtect(code, 4096, PAGE_EXECUTE_READ, &oldProtect);
// oldProtect now contains PAGE_READWRITE
// Execute the code
typedef int (*func_t)(void);
int result = ((func_t)code)(); // result = 42

Protection Constants

c
PAGE_NOACCESS // 0x01 - No access (guard page)
PAGE_READONLY // 0x02 - Read only
PAGE_READWRITE // 0x04 - Read and write
PAGE_WRITECOPY // 0x08 - Copy-on-write
PAGE_EXECUTE // 0x10 - Execute only
PAGE_EXECUTE_READ // 0x20 - Execute and read
PAGE_EXECUTE_READWRITE // 0x40 - Execute, read, and write
PAGE_EXECUTE_WRITECOPY // 0x80 - Execute, read, copy-on-write
// Modifier flags (combined with above using |):
PAGE_GUARD // 0x100 - Guard page (raises exception on first access)
PAGE_NOCACHE // 0x200 - Disable caching
PAGE_WRITECOMBINE // 0x400 - Write-combining (for GPU memory)
Key Concept
W^X (Write XOR Execute)

Modern security practice dictates that memory should never be simultaneously writable and executable (W^X). Malware and exploits often need to write shellcode and then execute it, which requires PAGE_EXECUTE_READWRITE. Legitimate JIT compilers follow the pattern: allocate as RW, write code, then change to RX. Data Execution Prevention (DEP) enforces that pages not marked executable cannot be executed.

VirtualFree: Releasing Memory

c
// Decommit pages (free their storage, keep reservation)
VirtualFree(ptr, 4096, MEM_DECOMMIT);
// The address range is still reserved, pages go back to PAGE_NOACCESS
// Can be recommitted later with VirtualAlloc MEM_COMMIT
// Release entire reservation (frees both committed storage and address space)
VirtualFree(base, 0, MEM_RELEASE);
// dwSize MUST be 0 when using MEM_RELEASE
// Releases the entire region that was reserved by VirtualAlloc

Put the three calls together and every page in your address space is in one of three states, which is exactly what VirtualQuery reports back in mbi.State:

Page states and the calls that move a page between them

Note the asymmetry. Commit and decommit work page by page, but MEM_RELEASE only goes back to MEM_FREE for the whole region at once, from the base address you got at reservation time.

Heap APIs: HeapCreate and HeapAlloc

For applications that need many small allocations (like malloc/free), Windows provides the Heap API:

c
// Create a private heap
HANDLE hHeap = HeapCreate(
0, // Options (HEAP_NO_SERIALIZE for single-threaded)
0, // Initial size (0 = one page)
0 // Maximum size (0 = growable)
);
// Allocate from the heap
void *ptr = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, 256);
// Reallocate
ptr = HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, ptr, 512);
// Free
HeapFree(hHeap, 0, ptr);
// Destroy the heap (frees ALL allocations in one shot)
HeapDestroy(hHeap);

The default process heap is available via GetProcessHeap(). The C runtime's malloc() and free() are typically implemented using HeapAlloc/HeapFree on the process heap.

Low-Fragmentation Heap (LFH)

Windows Vista+ enables the Low-Fragmentation Heap by default. The LFH uses size-based bucketing to reduce fragmentation:

text
LFH Buckets:
Bucket 1: 1-8 bytes → 8-byte blocks
Bucket 2: 9-16 bytes → 16-byte blocks
Bucket 3: 17-24 bytes → 24-byte blocks
...
Bucket 128: 15873-16384 → 16384-byte blocks
Allocations > 16 KB go to the back-end (regular heap)

The LFH also randomizes allocation order within buckets, providing some protection against heap exploitation techniques.

Memory-Mapped Files

Memory-mapped files allow you to access file data as if it were in memory:

c
// Step 1: Open the file
HANDLE hFile = CreateFile("data.bin",
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
// Step 2: Create a file mapping (section object)
HANDLE hMapping = CreateFileMapping(
hFile,
NULL, // Security
PAGE_READWRITE, // Protection
0, // Max size high DWORD
0, // Max size low DWORD (0 = file size)
NULL // Name (NULL = anonymous)
);
// Step 3: Map a view into memory
LPVOID view = MapViewOfFile(
hMapping,
FILE_MAP_ALL_ACCESS,
0, 0, // Offset (high, low)
0 // Size (0 = entire file)
);
// Access file data directly through memory
int *data = (int *)view;
data[0] = 42; // Writes to the file!
int value = data[100]; // Reads from the file
// Step 4: Cleanup
FlushViewOfFile(view, 0); // Force write to disk
UnmapViewOfFile(view);
CloseHandle(hMapping);
CloseHandle(hFile);

Shared Memory via File Mapping

Named file mappings enable shared memory between processes:

c
// Process A: Create named mapping backed by pagefile
HANDLE hShared = CreateFileMapping(
INVALID_HANDLE_VALUE, // Pagefile-backed (not a real file)
NULL,
PAGE_READWRITE,
0, 4096, // 4 KB
"Local\\MySharedData" // Name
);
LPVOID pShared = MapViewOfFile(hShared, FILE_MAP_ALL_ACCESS, 0, 0, 0);
strcpy((char *)pShared, "Hello from Process A!");
// Process B: Open existing mapping
HANDLE hShared = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE,
"Local\\MySharedData");
LPVOID pShared = MapViewOfFile(hShared, FILE_MAP_ALL_ACCESS, 0, 0, 0);
printf("Received: %s\n", (char *)pShared);

Working Sets and Memory Status

Querying Memory Information

c
// Query information about a virtual address
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(someAddress, &mbi, sizeof(mbi));
// mbi.BaseAddress - Base of the region
// mbi.RegionSize - Size of the region with same attributes
// mbi.State - MEM_COMMIT, MEM_RESERVE, or MEM_FREE
// mbi.Protect - PAGE_READWRITE, etc.
// mbi.Type - MEM_PRIVATE, MEM_MAPPED, or MEM_IMAGE
// Query global memory status
MEMORYSTATUSEX ms = { .dwLength = sizeof(ms) };
GlobalMemoryStatusEx(&ms);
// ms.dwMemoryLoad - Percentage of physical memory in use
// ms.ullTotalPhys - Total physical memory in bytes
// ms.ullAvailPhys - Available physical memory
// ms.ullTotalPageFile - Total pagefile size
// ms.ullAvailVirtual - Available virtual address space

Scanning Process Memory

This technique is used by debuggers, security tools, and memory editors:

c
MEMORY_BASIC_INFORMATION mbi;
LPVOID addr = NULL;
while (VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi))) {
if (mbi.State == MEM_COMMIT) {
printf("Region: %p, Size: %zu, Protect: %08X, Type: %s\n",
mbi.BaseAddress, mbi.RegionSize, mbi.Protect,
mbi.Type == MEM_IMAGE ? "Image" :
mbi.Type == MEM_MAPPED ? "Mapped" : "Private");
}
addr = (BYTE *)mbi.BaseAddress + mbi.RegionSize;
}

The Win32 memory management APIs underpin all memory operations on Windows. Knowing the reserve/commit model, page protections, and memory-mapped files is indispensable for systems programming, custom allocator design, and security analysis.