Virtual Memory & Paging

Memory in modern operating systems are not directly mapped with the physical memory ( .i.e. the RAM). Instead, virtual memory addresses are used by the processes that are mapped to physical memory addresses. Goal is to save as much as physical memory as possible.

Virtual memory relies on the concept of Memory Paging which divides memory into chunks of 4kb called pages.

image.png

Page State

Pages within a process’s virtual address space can be in one of the 3 states -

  1. Free - Neither committed nor reserved. This page is not accessible to the process. Attempting to read from or write to a free page can result in an access violation.
  2. Reserved - The page is reserved for future use. It is available to be committed. The range of addresses cannot be used by other allocation functions.
  3. Committed - Memory charges have been allocated from the overall size of RAM and paging files on disk. The page is accessible and access is controlled by memory protection constants.

Page Protection Options

  1. PAGE_NOACCESS
  2. PAGE_EXECUTE_READWRITE - It is generally marked as IoC because it’s uncommon to have R,W & X permissions at the same time.
  3. PAGE_READONLY

Allocating Memory Example

// Allocating memory buffer of 100 bytes

// Method - 1 : Using malloc()
PVOID pAddress = malloc(100);

// Method - 2 : Using HeapAlloc()
PVOID pAddress = HeapAlloc(GetProcessHeap(),0,100);

// Method - 3 : Using LocalAlloc()
PVOID pAddress = LocalAlloc(LPTR,100);

Memory allocation functions return the base address which is simply a pointer to the beginning of the memory block that was allocated.

image.png

#include <Windows.h>
#include <stdio.h>

int main() {
	PVOID pAddress = HeapAlloc(GetProcessHeap(), 0, 100);

	printf("Base Address of Allocated Memory: 0x%p\\n", pAddress);
	printf("Enter to quit...\\n");

	getchar();
	return 0;
}

Writing to Memory Example

PVOID pAddress = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,100);
const CHAR* cString = "Sushant is the best";
memcpy(pAddress,cString,strlen(cString));