为什么mmap()使用MAP_FAILED而不是NULL?

时间:2023-01-25 02:43:10

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.

有谁知道为什么mmap()返回MAP_FAILED而不是NULL?在大多数系统上,似乎MAP_FAILED是(void *) - 1。为什么mmap()不使用NULL代替?我知道地址0x0在技术上是一个有效的内存页面,而(void *) - 1永远不会是一个有效的页面。但我的猜测是mmap()实际上永远不会实际返回页面0x0。例如,在Windows上,VirtualAlloc()在出错时返回NULL。

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.

假设mmap()永远不会返回0x0是否安全?大概是对mmap()的成功调用应该将可用内存返回给调用者。地址0x0永远不可用,因此成功时永远不应返回。这种情况会让使用0x0作为失败的哨兵似乎是明智的,这就是为什么我首先对MAP_FAILED的存在感到困惑。

1 个解决方案

#1


7  

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.

在某些罕见的情况下,mmap()实际上会在地址0x0处创建映射。目前,它通常需要root权限(或者在Linux系统上将mmap_min_addr sysctl设置为零),但这是可能的。如果创建了这样的映射,则可以写入该地址。

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

另一方面,MAP_FAILED永远不是mmap()的有效返回值,因此它可用作标记。

#1


7  

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.

在某些罕见的情况下,mmap()实际上会在地址0x0处创建映射。目前,它通常需要root权限(或者在Linux系统上将mmap_min_addr sysctl设置为零),但这是可能的。如果创建了这样的映射,则可以写入该地址。

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

另一方面,MAP_FAILED永远不是mmap()的有效返回值,因此它可用作标记。