#include <windows.h>
#include <stdio.h>
#include <string.h>
int main(void) {
SIZE_T size = 1024; // allocate 1 KB
// Allocate memory
void* mem = VirtualAlloc(
NULL, // let Windows choose the address
size, // number of bytes
MEM_RESERVE | MEM_COMMIT, // reserve + commit
PAGE_READWRITE // memory protection
);
if (mem == NULL) {
printf("VirtualAlloc failed: %lu\n", GetLastError());
return 1;
}
printf("Allocated at: %p\n", mem);
// Use the memory
char* buffer = (char*)mem;
strcpy_s(buffer, size,
"VirtualAlloc is a low-level Windows API function used to allocate memory");
printf("%s\n", buffer);
// Free the memory
if (!VirtualFree(mem, 0, MEM_RELEASE)) {
printf("VirtualFree failed: %lu\n", GetLastError());
}
return 0;
}
/*
run:
Allocated at: 000002946F260000
VirtualAlloc is a low-level Windows API function used to allocate memory
*/