Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 755
user3573388 Avatar asked Nov 09 '22 22:11

user3573388


1 Answers

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 by sysconf(_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.

like image 131
abligh Avatar answered Nov 14 '22 22:11

abligh