16

What does this line of code do?

mmap(NULL, n, PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065

2 Answers2

18

It requests a private, writeable anonymous mapping of n bytes of memory.

  • A private mapping means it's not shared with other processes (eg, after a fork() the child and parent will have independent mappings);
  • An anonymous mapping means that it's not backed by a file.

In this case, it is essentially requesting a block of n bytes of memory, so roughly equivalent to malloc(n) (although it must be freed with munmap() rather than free(), and it will be page-aligned). It's also requesting that the memory be writeable but not requesting that it be readable, however writeable and unreadable memory is typically not a combination supported by the underlying hardware. When PROT_WRITE alone is requested, POSIX allows the implementation to supply memory that can also be read and/or executable.

caf
  • 233,326
  • 40
  • 323
  • 462
12

man mmap will help you here.

It creates a memory mapping in the virtual address space of the process. It's creating an anonymous mapping, which is rather like using malloc to allocate n bytes of memory.

The parameters are:

  • NULL - the kernel will choose an address for the mapping
  • n - length of the mapping (in bytes)
  • PROT_WRITE - pages may be written
  • MAP_ANON | MAP_PRIVATE - mapping is not backed by a file, and updates written to the mapping are private to the process
  • -1 - the file descriptor; not used because the mapping is not backed by a file
  • 0 - offset within the file at which to start the mapping - again, not used, because the mapping is not backed by a file
Richard Fearn
  • 25,073
  • 7
  • 56
  • 55