malloc() 分配的缓冲区是否可能与使用 mmap() 分配的另一个缓冲区重叠?
我计划使用 mmap() 来分配靠近特定地址的缓冲区。
我担心的是,使用 mmap() 分配的缓冲区将与 malloc() 或 new 运算符(C++)分配的其他缓冲区重叠。是否可以?
I plan to use mmap() to allocate a buffer close to a specific address.
What I'm worried about is, the buffer allocated using mmap() will overlap other buffers allocated by malloc() or new operator (C++). Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用
MAP_FIXED
要求mmap
在特定地址创建映射,那么是的您可能会覆盖现有映射,例如空间由malloc
分配,共享库代码或数据部分等的一部分。基本上,使用MAP_FIXED
总是错误的,除非您已经通过调用获得了地址范围到mmap
而不指定MAP_FIXED
(这样你就知道它属于你);在这种情况下,您可以使用 MAP_FIXED 有意覆盖部分映射)。其他答案似乎都忽略了您所说的“靠近特定地址”这一事实,这对我来说意味着
MAP_FIXED
。如果您不使用MAP_FIXED
,请详细说明如何获取“靠近特定地址”的映射。If you use
MAP_FIXED
to demandmmap
create the mapping at a particular address, then yes it is possible that you overwrite an existing mapping such as space allocated bymalloc
, part of a shared library's code or data section, etc. Basically it's always an error to useMAP_FIXED
unless you've already obtained the address range via a call tommap
without specifyingMAP_FIXED
(so you know it belongs to you); in this case you can intentionally overwrite parts of the mapping usingMAP_FIXED
).The other answers all seemed to miss the fact that you said "close to a specific address", which to me implies
MAP_FIXED
. If you're not usingMAP_FIXED
, please elaborate on how you're obtaining a mapping "close to a specific address".不,那不会发生。
由
malloc
函数维护的堆位于通过brk
或mmap
建立的虚拟映射中,因此只有在以下情况下才能重用内存区域:内核通过 mmap 两次给出相同的块。No, that does not happen.
The heap maintained by the
malloc
function lives in virtual mappings that have been established viabrk
ormmap
, so memory areas could only be reused if the kernel gave out the same block viammap
twice.您必须使用 malloc 分配映射的内存。分配的内存不会重叠。所以不,你会没事的。
You must allocate the memory that is mapped, with malloc. malloced memory won't overlap. So no, you'll be fine.