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.
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.
2 Answers
Reset to default 2The pointer has to be page size aligned.
void handleMincoreError(int errCode)
{
switch (errCode)
{
case EAGAIN:
fprintf(stderr, "mincore failed: Resources temporarily unavailable (EAGAIN). Try again later.\n");
break;
case EFAULT:
fprintf(stderr, "mincore failed: The specified address range is not fully allocated (EFAULT).\n");
break;
case EINVAL:
fprintf(stderr, "mincore failed: The address is not aligned or allocated_size is invalid (EINVAL).\n");
break;
case ENOMEM:
fprintf(stderr, "mincore failed: Memory mapping failed, possibly due to lack of memory (ENOMEM).\n");
break;
default:
fprintf(stderr, "mincore failed: %s (errno: %d)\n", strerror(errCode), errCode);
break;
}
}
void* alignToPage(void* addr)
{
size_t pageSize = getpagesize();
return (void*)((uintptr_t)addr & ~(pageSize - 1));
}
int main(int argc, char **argv) {
char *ptr;
unsigned int num_of_byte_allocated = 512;
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));
int err;
ptr = malloc(allocated_size);
if (!ptr) {
perror("malloc failed");
}
if ((err = mincore(alignToPage(ptr), allocated_size, vec)))
{
handleMincoreError(errno);
}
/*....*/
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.