Overview
System memory is the primary resource used by operating systems and applications to store and retrieve data. Understanding how memory is allocated, managed, and accessed is essential for writing efficient, reliable software.
Memory Architecture
Modern computers use a hierarchical memory model:
- Registers β Fastest, located inside the CPU.
- Cache β L1, L2, L3 caches reduce latency.
- Main Memory (RAM) β Volatile storage for active processes.
- Virtual Memory β Extends RAM using disk storage.
Virtual memory allows each process to operate in its own isolated address space, enabling features like paging and memory protection.
Memory Management API (C++)
Windows provides a set of functions for lowβlevel memory handling. Below is a summary of the most common API calls.
#include <windows.h>
// Allocate memory
LPVOID ptr = VirtualAlloc(
nullptr, // system chooses address
1024, // size in bytes
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
// Free memory
if (ptr) {
VirtualFree(ptr, 0, MEM_RELEASE);
}
// Change protection
DWORD oldProtect;
VirtualProtect(ptr, 1024, PAGE_READONLY, &oldProtect);
Sample: Simple Memory Pool
This example demonstrates a basic memory pool implementation using C++.
#include <cstdlib>
#include <vector>
#include <mutex>
class MemoryPool {
public:
MemoryPool(std::size_t blockSize, std::size_t blockCount)
: blockSize_(blockSize), pool_(blockCount) {
for (auto &ptr : pool_) {
ptr = std::malloc(blockSize_);
}
}
~MemoryPool() {
for (auto &ptr : pool_) {
std::free(ptr);
}
}
void* acquire() {
std::lock_guard<std::mutex> lock(mtx_);
if (freeList_.empty()) return nullptr;
void* p = freeList_.back();
freeList_.pop_back();
return p;
}
void release(void* p) {
std::lock_guard<std::mutex> lock(mtx_);
freeList_.push_back(p);
}
private:
std::size_t blockSize_;
std::vector<void*> pool_;
std::vector<void*> freeList_;
std::mutex mtx_;
};