Full Page Malloc
c, malloc, memory, page-size
Solution
The `malloc` function doesn't have any concept of pagesize. Unless you are allocating pages that are ALSO aligned to a page-boundary, you will not get ANY benefit from calling `malloc` in this way. Just `malloc` as many elements as you need, and stop worrying about micro-optimising something that almost certainly won't give you any benefit at all.
Yes, the Linux kernel does things like this all the time. There are two reasons for that:
- You don't want to allocate blocks LARGER than a page, since that significantly increases the risk of allocation failure.
- The kernel allocation is made on a per-page basis, rather than like the C library, which allocates a large amount of memory in one go, and then splits it into small components.
If you really want to allocate page-size amount of memory, then use the result from `sysconf(_SC_PAGESIZE)` as your size argument. But it is almost certain that your allocation straddles two pages.
Problem
I am trying to optimize the memory allocation of my program by using entire pages at a time. I am grabbing the page size like this: `sysconf(_SC_PAGESIZE);` then calculating the total number of elements that will fit in a page like this: `elements=pageSize/sizeof(Node);` I was thinking that when I actually go to malloc my memory I would use `malloc(elements*sizeof(Node));` It seems like the multiplication and division of sifeof(Node) would cancel out, but with integer division, I do not believe that that is the case. Is this the best way to malloc an entire page at a time? Thanks