20

Does anybody know why mmap() returns MAP_FAILED instead of NULL? It seems that MAP_FAILED is (void*)-1 on most systems. Why doesn't mmap() just use NULL instead? I know that address 0x0 is technically a valid memory page, whereas (void*)-1 will never be a valid page. Yet my guess is that mmap() will never actually return page 0x0 in practice. On Windows, for example, VirtualAlloc() returns NULL on error.

Is it safe to assume that mmap() will never return 0x0? Presumably a successful call to mmap() ought to return usable memory to the caller. Address 0x0 is never usable, so it should never be returned upon success. That circumstance would make it seem sensible to use 0x0 as the failure-sentinel, which is why I'm puzzled by the existence of MAP_FAILED in the first place.

fieldtensor
  • 3,972
  • 4
  • 27
  • 43

1 Answers1

21

There are some rare situations where mmap() will actually create a mapping at address 0x0. These days, it typically requires root privileges (or for the mmap_min_addr sysctl to be set to zero on Linux systems) but it is possible. If such a mapping is created, it becomes possible to write to this address.

MAP_FAILED, on the other hand, is never a valid return value from mmap(), so it's usable as a sentinel.

  • That's very interesting about mmap_min_addr. So it seems that you can indeed request a mapping at address 0x0 in some cases. Given that, allow me to give more specificity to my question. I asked about whether mmap() will ever return NULL in practice, but what I really meant to ask if about whether or not a MAP_ANON call like mmap(NULL, size, flags, MAP_ANON | MAP_PRIVATE, -1, 0) will ever return null in practice. That's my actual use case, so that's what I'm really curious about. – fieldtensor Jul 03 '14 at 21:54
  • 2
    No, `mmap()` will never return a mapping at that address unless you ask for it with `MAP_FIXED`. –  Jul 03 '14 at 21:56
  • 1
    @duskwuff I'm pretty sure you're right, but do you have a source for that? – Guido Jul 15 '14 at 19:17
  • 3
    @Guido From [the spec](http://pubs.opengroup.org/onlinepubs/009695399/functions/mmap.html): "When the implementation selects a value for `pa`, it never places a mapping at address 0." –  Jul 15 '14 at 19:28