#include <windows.h>
#include <iostream>
int main() {
SIZE_T size = 1024; // allocate 1 KB
// Allocate memory
void* mem = VirtualAlloc(
nullptr, // let Windows choose the address
size, // number of bytes
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE // memory protection
);
if (!mem) {
std::cerr << "VirtualAlloc failed: " << GetLastError() << "\n";
return 1;
}
std::cout << "Allocated at: " << mem << "\n";
// Use the memory
char* buffer = static_cast<char*>(mem);
strcpy_s(buffer, size, "VirtualAlloc is a low-level Windows API function used to allocate memory");
std::cout << buffer << "\n";
// Free the memory
BOOL ok = VirtualFree(mem, 0, MEM_RELEASE);
if (!ok) {
std::cerr << "VirtualFree failed: " << GetLastError() << "\n";
}
return 0;
}
/*
run:
Allocated at: 000002455A430000
VirtualAlloc is a low-level Windows API function used to allocate memory
*/