Is the length in mmap a number of bytes or a number of pages?

In the function:

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

Does the argument length in mmap represent a number of bytes or a number of pages? Also, can I use mmap similarly to malloc? What are the differences?

Upvotes: 1

Views: 3009

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58473

The length parameter is in bytes. The Linux man page does not say this explicitly, but the POSIX spec says (emphasis mine):

The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes.

It is possible to use mmap as a way to allocate memory (you'll want to use MAP_ANONYMOUS or else map the /dev/zero device), but it's not in general a good direct replacement for malloc:

  • Mappings will always be made in page units (so the system will round up length to the next multiple of the page size), so it's very inefficient for small allocations.

  • You can't pass pointers returned by mmap to realloc or free (use mremap and munmap instead).

  • munmap actually returns memory to the system, whereas free may potentially keep it assigned to your process and just mark it available for use by future calls to malloc. This has pros and cons. On the one hand, if you know you will not be needing that memory in the future, it is nice to let the system have it back. On the other hand, every mmap/munmap requires a system call, which is relatively slow, whereas malloc may be able to allocate previously freed memory that already belongs to your process without a system call.

Upvotes: 6

Related Questions