Mapping memory with mmap
A process begins life with a certain amount of memory mapped to the text (the code) and data segments of the program file, together with the shared libraries that it is linked with. It can allocate memory on its heap at runtime using malloc(3)
and on the stack through locally scoped variables and memory allocated through alloca(3)
. It may also load libraries dynamically at runtime using dlopen(3)
. All of these mappings are taken care of by the kernel. However, a process can also manipulate its memory map in an explicit way using mmap(2)
:
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
This function maps length
bytes of memory from the file with the fd
descriptor, starting at offset
in the file, and returns a pointer to the mapping, assuming it is successful. Since the underlying hardware works in pages, length
is rounded up to the nearest whole number of pages. The protection parameter, prot
, is a combination of read...