Reputation: 15
I was searching for a solution to a problem which I found in another post. This code was posted Jerry Coffin. However, I have difficulty in understanding the "show_page()" and the "alloc_page" functions.
#include <windows.h>
#include <iostream>
#include <iomanip>
std::ostream &operator<<(std::ostream &os, MEMORY_BASIC_INFORMATION const &mi) {
return os << std::setw(20) << "Allocation Base: " << mi.AllocationBase << "\n"
<< std::setw(20) << "BaseAddress: " << mi.BaseAddress << "\n"
<< std::setw(20) << "Protection: " << mi.Protect << "\n"
<< std::setw(20) << "Region size: " << mi.RegionSize;
}
void show_page(void *page) {
MEMORY_BASIC_INFORMATION info;
VirtualQuery(page, &info, sizeof(info));
std::cout << info << "\n\n";
}
static const int page_size = 4096;
void *alloc_page(char *address) {
void *ret = VirtualAlloc(address, page_size, MEM_COMMIT, PAGE_READWRITE);
show_page(ret);
return ret;
}
int main() {
static const int region_size = 65536;
char * alloc = static_cast<char *>(VirtualAlloc(NULL, region_size, MEM_RESERVE, PAGE_READWRITE));
for (int i = 0; i < 4; i++)
alloc_page(alloc + page_size * i);
}
I am a beginner C++ programmer and trying to understand VirtualAlloc to allocate contiguous pages of memory.
Upvotes: 0
Views: 446