I'm building a custom implementation of malloc
using mmap.
If the user wants to allocate 500 bytes of memory, i call mmap(0, 500, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)
. mmap
returns a pointer to a block with size 4096 (if that is the page size).
In my linked list I want to have one block set to 500 bytes marked as taken, and one block set to 4096-500=3596 bytes marked as free. It is not clear, however how much memory mmap
really allocates. How can I get that information?
The prototype of mmap()
is:
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);`
Technically you are guaranteed only that it will allocate length
bytes. However, in practice it allocates whole pages (i.e. multiples of PAGE_SIZE
) though you are not guaranteed you can use anything beyond length
. Indeed per the man page:
offset
must be a multiple of the page size as returned bysysconf(_SC_PAGE_SIZE)
.
Note that there is no restriction on length
being a multiple of PAGE_SIZE
but you might as well round up length
to a multiple of PAGE_SIZE
(as that's what's going to be allocated anyway), in which case the amount of memory allocated is exactly length
. If you don't do that, it will allocate the minimum number of whole pages that contain length
bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With