How can I get the number of bytes allocated by mmap?

I am creating a custom implementation 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 4096 block (if it is a page size).

In my linked list, I want one block to be set to 500 bytes marked as accepted and one block to be set to 4096-500 = 3596 bytes marked free. It is not clear, however, how much memory is mmap

actually allocated. How can I get this information?

+3


source to share


1 answer


The prototype mmap()

is:

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);`

      

Technically, you are only guaranteed that it will allocate length

bytes. In practice, however, it allocates entire pages (i.e., Multiples PAGE_SIZE

), although you're not guaranteed to be able to use anything outside of it length

. Indeed, from the man page:



offset

must be a multiple of the page size returned sysconf(_SC_PAGE_SIZE)

.

Note that the limit length

on is length

not a multiple PAGE_SIZE

, but you can round length

to a multiple PAGE_SIZE

(since that will still be allocated), where if the allocated memory is length

. If you don't, it will allocate the minimum number of whole pages containing length

bytes.

0


source







All Articles