【C++】堆和栈的区别

正确来说是堆内存分配和栈内存分配的区别。为了练习英文能力,所以作者我下面用英文来记录:

(ps:中文解释链接http://baike.baidu.com/view/93201.htm)

1.What is the question?

The difference between stack and heap  memory allocation?

Programming language books usually explain that value types are created on the stack, and reference types are created on the heap.But i haven't read a clear explanation of this .

2.The answers i find and  think are easily understand.

The stack is the memory set aside as scratch space for a thread of execution.When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns,the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer;


The heap is memory set aside for dynamic allocation.Unlike the stack,there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

3.Related Question:what makes one faster?

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it(a pointer/integer is simply incremented or decremented),while the heap has much more  complex bookkeeping involved in an allocation or free.Also, each byte in the stack tends to be reused  very frequently which means it tends to be mapped to the processor's cache,making it very fast.


link to this question:http://timmurphy.org/2010/08/11/the-difference-between-stack-and-heap-memory-allocation/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值