Why does mmap() use MAP_FAILED instead of NULL?

有些话、适合烂在心里 提交于 2019-12-12 08:23:18

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24562691/why-does-mmap-use-map-failed-instead-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!