example/mem_ops/mem_ops.cpp (26 lines of code) (raw):
#include <windows.h>
#include <iostream>
int main()
{
// 1. Allocate memory with VirtualAlloc
SIZE_T size = 0x400; // Allocate 1024 bytes
void* ptr = VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (ptr == nullptr) {
std::cerr << "Memory allocation failed with error: " << GetLastError() << std::endl;
return 1;
}
std::cout << "Memory allocated at: " << ptr << std::endl;
// 2. Use the allocated memory (example: write data)
strcpy_s(static_cast<char*>(ptr), size, "Hello, Virtual Memory!");
// 3. Change the protection of the allocated memory with VirtualProtect
DWORD oldProtect;
if (VirtualProtect(ptr, size, PAGE_READONLY, &oldProtect)) {
std::cout << "Memory protection changed to read-only." << std::endl;
} else {
std::cerr << "Changing memory protection failed with error: " << GetLastError() << std::endl;
}
// Accessing memory after changing protection to PAGE_READONLY
std::cout << "Data in memory: " << static_cast<char*>(ptr) << std::endl;
// 4. Free the allocated memory with VirtualFree
if (VirtualFree(ptr, 0, MEM_RELEASE)) {
std::cout << "Memory freed successfully." << std::endl;
} else {
std::cerr << "Memory freeing failed with error: " << GetLastError() << std::endl;
}
return 0;
}