0

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.

nab saw
  • 15
  • 3
  • 1
    Have you tried to read [the documentation for `VirtualAlloc`](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc)? – Some programmer dude Dec 21 '21 at 11:52
  • 1
    Please link the origin of that code as well! Also, I wonder why you want to allocate contiguous pages of memory, especially as a beginner. That's rather advanced device-driver stuff, IMHO. Also, you're not really asking a question, so please take the [tour] and read [ask]. – Ulrich Eckhardt Dec 21 '21 at 11:52
  • 1
    I'd also like to point out that VirtualAlloc is not exactly a beginner topic. – Sebastian Redl Dec 21 '21 at 11:52
  • Start from the basic topics. Learn how `new()` and `delete()` and `malloc()`, etc. work. Don't jump onto advanced topics without having a good understanding of the basics. – digito_evo Dec 21 '21 at 11:59
  • `a solution to a problem` - which problem? – 500 - Internal Server Error Dec 21 '21 at 12:10
  • Have you searched the Internet to find out about `VirtualAlloc`? What have you found, and what of this you don't understand? – zkoza Dec 29 '21 at 14:38

0 Answers0