Why does mmap () use MAP_FAILED instead of NULL?

Does anyone know why mmap () returns MAP_FAILED instead of NULL? MAP_FAILED (void *) seems to be 1 on most systems. Why is null used instead of mmap ()? I know that address 0x0 is a technically valid memory page, whereas (void *) - 1 will never be a valid page. However, I assume that mmap () will never return a 0x0 page in practice. On Windows, for example, VirtualAlloc () returns NULL on error.

Can we assume that mmap () will never return 0x0? Presumably, a successful mmap () call should return useful memory to the caller. Address 0x0 is never used, so it should never be returned after success. This would make it reasonable to use 0x0 as a failure-loser, so I am puzzled by the existence of MAP_FAILED in the first place.

+6
source share
1 answer

There are a few rare situations where mmap() actually creates a mapping at 0x0. These days, root privileges are usually required (or for the mmap_min_addr sysctl parameter, which should be set to zero on Linux systems), but this 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 can be used as a sentinel.

+6
source

Source: https://habr.com/ru/post/971727/


All Articles