detecting the memory page size

14,062

Solution 1

Since Boost is a pretty portable library you could use mapped_region::get_page_size() function to retrieve the memory page size.

As for C++ Standard it gives no such a possibility.

Solution 2

C doesn't know anything about memory pages. On posix systems you can use long pagesize = sysconf(_SC_PAGE_SIZE);

Solution 3

Windows 10, Visual Studio 2017, C++. Get the page size in bytes.

int main()
{
    SYSTEM_INFO sysInfo;

    GetSystemInfo(&sysInfo);

    printf("%s %d\n\n", "PageSize[Bytes] :", sysInfo.dwPageSize);

    getchar();

    return 0;
}

Solution 4

Yes, this is platform-specific. On Linux there's sysconf(_SC_PAGESIZE), which also seems to be POSIX. A typical C library implements this using the auxiliary vector. If for some reason you don't have a C library or the auxiliary vector you could determine the page size like this:

size_t get_page_size(void)
{
    size_t n;
    char *p;
    int u;
    for (n = 1; n; n *= 2) {
        p = mmap(0, n * 2, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
        if (p == MAP_FAILED)
            return -1;
        u = munmap(p + n, n);
        munmap(p, n * 2);
        if (!u)
            return n;
    }
    return -1;
}

That's also POSIX, I think. It relies on there being some free memory, but it only needs two consecutive pages. It might be useful in some (weird) circumstances.

Solution 5

Across operating systems, no.

On Linux systems:

#include <unistd.h>
long sz = sysconf (_SC_PAGESIZE);
Share:
14,062
Franck Freiburger
Author by

Franck Freiburger

Computer enthusiast, I followed my studies in this field and gained twenty years of experience in business as a confirmed software engineer in web and desktop technologies. I have also realized many personal innovative projects and also open-source such as jslibs. The management of these projects made me want to become independent and to create my own company in order to vary my projects and offer my expertise in computing. I propose the development of professional applications and websites thanks to innovative technologies like HTML5, CSS3, ES6 and Node.js, guaranteeing an optimal and tailored result.

Updated on June 01, 2022

Comments

  • Franck Freiburger
    Franck Freiburger almost 2 years

    Is there a portable way to detect (programmatically) the memory page size using C or C++ code ?

    • Admin
      Admin almost 14 years
      No, there isn't.
    • zvrba
      zvrba almost 14 years
      No there isn't because C and C++ exist also for platforms without virtual memory.
  • kfsone
    kfsone over 10 years
    Question says 'C', 'C++' and 'portable' and on top of that you managed to not even describe how to get from that to a page size.
  • kfsone
    kfsone over 10 years
    Disconnect between your explanation and the conclusion; applying the same logic would tell us that determining the size of a pointer is platform specific.