Search code examples
cposixmmap

What is the significance of the memory-map length when using the mmap API?


In POSIX, you have this nice mmap() API. The documentation is not clear whether the value of length has an impact on memory/performance. Please advise!

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

Consider a file of 10 MB where I need to map only a subset of it, like 2 MB. Also, let's assume that we never try to access memory outside the 2 MB bounds. (Doing so obviously has an impact.)


Q: Does it matter if the length is set to 2 or 10 MB?


Solution

  • The length parameter tells how much contiguous space starting from offset should be mapped into the memory. Mapping only first 2M of a file that has length of 10M shouldn't have adverse performance characteristics compared to mapping 10M, other than if you need to change the mapping later to read the other parts.

    One reason for the length parameter is to avoid accessing parts that you don't want to access even by accident. Another reason is if you've got a 6G file and on a 32-bit processor, then good luck trying to map all of that 6G into 2-4G user space.