为什么mmap()使用MAP_FAILED而不是NULL? [英] Why does mmap() use MAP_FAILED instead of NULL?

查看:1427
本文介绍了为什么mmap()使用MAP_FAILED而不是NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()永远不会返回0x0吗?大概,对mmap()的成功调用应该将可用内存返回给调用方.地址0x0永远无法使用,因此成功后绝不能返回.这种情况使使用0x0作为故障前兆似乎是明智的,这就是为什么我首先对MAP_FAILED的存在感到困惑.

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处创建映射.如今,它通常需要root特权(或在Linux系统上将mmap_min_addr sysctl设置为零),但是有可能.如果创建了这样的映射,则可以写入该地址.

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永远不是mmap()的有效返回值,因此它可用作哨兵.

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

这篇关于为什么mmap()使用MAP_FAILED而不是NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆