Skip to content
systemcoding.dev
Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read
Summarize in AI

Every mmap length, alignment and madvise range is measured in pages, so a program needs the page size. The portable call is sysconf(3) with _SC_PAGESIZE. It returns a long, and on failure -1.

pagesize.cc
#include <stdio.h>
#include <unistd.h>

int main(void) {
    long page = sysconf(_SC_PAGESIZE);
    if (page < 0) {
        perror("sysconf");
        return 1;
    }
    printf("page size: %ld\n", page);
    return 0;
}
Text
page size: 4096

That is the result on x86-64. The number is not a constant of the architecture. An arm64 Linux kernel can be built for 4 KiB, 16 KiB or 64 KiB pages, and some distributions ship the larger sizes, so code that hard-codes 4096 passes on a laptop and fails with EINVAL from munmap or mmap on that kernel. The kernel passes the value to user space in the auxiliary vector (AT_PAGESZ), and glibc reads it from there, so the call costs no system call.

Cache the result in a static if you use it often, and compute masks from it, as in page - 1, rather than from a literal. Avoid getpagesize, which POSIX marked obsolescent in 2001 and removed in POSIX.1-2008. PAGE_SIZE from <sys/user.h> or <asm/page.h> is a build-time constant and has the same problem.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.