Search code examples
cmemorymalloc

Cannot use mincore to check whether page allocated by malloc is in ram


Question: Why do mincore failed with "Invalid argument" in the following code?

int main(int argc, char **argv) {
    char *ptr;
    unsigned int num_of_byte_allocated = 4;
    size_t page_size = getpagesize();
    size_t allocated_size = num_of_byte_allocated * page_size;
    unsigned char *vec = calloc(num_of_byte_allocated, sizeof(unsigned char));

    ptr = malloc(allocated_size);
    if (!ptr) {
       perror("malloc failed");
    }

    if (mincore(ptr, allocated_size, vec) == -1) {
        perror("mincore failed");
    } else {
        for (int i = 0; i < num_of_byte_allocated; i++) {
            printf("Page[%i]: %i\n", i, ptr[i] & 1);
        }
    }
}

However when I allocate with mmap then it works.


Solution

  • mincore requires the first address it is passed to be a multiple of the page size. malloc does not generally return an address that is page-aligned, even if the requested allocation amount is a multiple of the page size.