Reputation: 1297
How do I know page size of a unix machine, using malloc()?
Upvotes: 1
Views: 1174
Reputation: 34744
I guess if you allocate a buffer large enough, it'll have to get another few pages and then it'll put the buffer at the start of the first page. So you can allocate two very large buffers, remove the buffer header offset and then GCD the two buffers. Worked out pretty nicely on my system.
#include <stdlib.h>
#include <stdio.h>
unsigned gcd(unsigned a, unsigned b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
void main() {
void *p1 = malloc(1000000);
void *p2 = malloc(1000000);
unsigned p1r = (unsigned) p1 & 0xfffffff0;
unsigned p2r = (unsigned) p2 & 0xfffffff0;
printf("page size = %u\n", getpagesize());
printf("p1 = %p, p2 = %p\n", p1, p2);
printf("p1r = %p, p2r = %p\n", p1r, p2r);
printf("gcd = %u\n", gcd(p1r, p2r));
}
Upvotes: 3
Reputation: 6481
I don't know what malloc has to do with it, however:
#include <unistd.h>
(size_t) sysconf(_SC_PAGESIZE);
Upvotes: 2