为什么堆需要额外的内存来管理,而栈则不需要?
我读过一篇文章,说堆上分配的内存需要额外的内存进行管理。
比如说,如果我们尝试分配
200 个字节,则会额外分配 8 个字节用于内存管理。
但堆栈不需要这个额外的空间。
我知道堆栈地址从高=>低,但堆低=>高,但为什么堆上需要额外的空间?
I read an article that says memory allocated on heap needs additional memory for management.
Say,if we try to allocate
200 bytes,there'll be additional 8 bytes allocated for memory management.
But stack doesn't require this additional space.
I know stack addresses from high=>low,but heap low=>high,but why is the additional space needed on heap?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
堆栈变量作为堆栈帧的一部分进行分配,并在
ret
上消失。这实际上并不是 100% 免费;有一个寄存器跟踪堆栈帧的开始位置(x86 上的%ebp
),并且需要在函数入口处保存并在退出之前恢复;但它是针对每个函数而不是每个分配,并且跟踪帧基指针的用途不仅仅是这个(特别是,它用于在异常处理期间展开堆栈),因此它是沉没成本。Stack variables are allocated as part of the stack frame, which goes away on
ret
. This isn't actually 100% free; there's a register which keeps track of where the stack frame starts (%ebp
on x86) and it needs to be saved on function entry and restored before exit; but it's per function instead of per allocation, and tracking the frame base pointer is useful for more than just this (in particular, it's used to unwind the stack during exception handling), so it's something of a sunk cost.堆栈更易于管理(您总是从顶部分配/释放)并且堆栈已经由堆栈指针管理。这就是为什么它需要比堆更少的“管理空间”,在堆中你基本上可以自由地做任何事情。
The stack is simpler to manage (you always allocate/free from the top) and the stack is already managed by the stack pointer. That is why is needs less "administration space" than the heap where you are basically free to do anything.