简体   繁体   中英

How can I get the beginning of the page of a memory address?

I am trying to get the beginning of the page, which my memory address is stored in. How can I do that? (Windows x64)

First step is to find out the size of the memory page. There is no standard way to get the size of the memory page in C++. Consult documentation of the target operating system.

With the size of the page known, we need to align the given pointer to the edge of the page size. There is a standard function std::align which almost does what we want, except it aligns forwards the end of the page rather than back to the beginning. We can simply adjust one page backwards:

inline void*
align_back(void* address, std::size_t alignment) noexcept
{
    void* aligned = address;
    std::size_t space = alignment;
    std::align(alignment, 1, aligned, space);
    return address == aligned
        ? aligned
        : static_cast<char*>(aligned) - alignment;
}

// example
void* beginning = align_back(address, page_size);

Or, we can rely a bit on implementation dependent details and assume that alignment of a reinterpreted integer matches the alignment of the pointer:

inline void*
align_back(void* ptr, std::size_t alignment) noexcept
{
    std::uintptr_t ptr_int = reinterpret_cast<std::uintptr_t>(ptr);
    std::size_t remainder = ptr_int % alignment;
    return static_cast<char*>(ptr) - remainder;
}

This tends to produce better assembly in my testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM