What’s the difference between a stack and a heap?

The differences between the stack and the heap can be confusing for many people. So, we thought we would have a list of questions and answers about stacks and heaps that we thought would be very helpful.

Where are the stack and heap stored?

They are both stored in the computer’s RAM (Random Access Memory). For a refresher on RAM and virtual memory, read this article: How Virtual Memory Works

How do threads interact with the stack and the heap? How do the stack and heap work in multithreading?

In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap. Because the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they don’t try to access and manipulate the same piece(s) of memory in the heap at the same time.

Can an object be stored on the stack instead of the heap?

Yes, an object can be stored on the stack. If you create an object inside a function without using the “new” operator then this will create and store the object on the stack, and not on the heap. Suppose we have a C++ class called Member, for which we want to create an object. We also have a function called somefunction( ). Here is what the code would look like:

Code to create an object on the stack:

void somefunction( )
{
/* create an object "m" of class Member
this will be put on the stack since the
"new" keyword is not used, and we are
creating the object inside a function
*/ Member m; } //the object "m" is destroyed once the function ends

So, the object “m” is destroyed once the function has run to completion – or, in other words, when it “goes out of scope”. The memory being used for the object “m” on the stack will be removed once the function is done running.

If we want to create an object on the heap inside a function, then this is what the code would look like:

Code to create an object on the heap:

void somefunction( )
{
/* create an object "m" of class Member
this will be put on the heap since the
"new" keyword is used, and we are
creating the object inside a function
*/ Member* m = new Member( ) ; /* the object "m" must be deleted
otherwise a memory leak occurs
*/ delete m;
}

In the code above, you can see that the “m” object is created inside a function using the “new” keyword. This means that “m” will be created on the heap. But, since “m” is created using the “new” keyword, that also means that we must delete the “m” object on our own as well – otherwise we will end up with a memory leak.

How long does memory on the stack last versus memory on the heap?

Once a function call runs to completion, any data on the stack created specifically for that function call will automatically be deleted. Any data on the heap will remain there until it’s manually deleted by the programmer.

Can the stack grow in size? Can the heap grow in size?

The stack is set to a fixed size, and can not grow past it’s fixed size (although some languages have extensions that do allow this). So, if there is not enough room on the stack to handle the memory being assigned to it, a stack overflowoccurs. This often happens when a lot of nested functions are being called, or if there is an infinite recursive call.

If the current size of the heap is too small to accommodate new memory, then more memory can be added to the heap by the operating system. This is one of the big differences between the heap and the stack.

How are the stack and heap implemented?

The implementation really depends on the language, compiler, and run-time – the smalldetails of the implementation for a stack and a heap will always be different depending on what language and compiler are being used. But, in the big picture, the stacks and heaps in one language are used to accomplish the same things as stacks and heaps in another language.

Which is faster – the stack or the heap? And why?

The stack is much faster than the heap. This is because of the way that memory is allocated on the stack. Allocating memory on the stack is as simple as moving the stack pointer up.

How is memory deallocated on the stack and heap?

Data on the stack is automatically deallocated when variables go out of scope. However, in languages like C and C++, data stored on the heap has to be deleted manually by the programmer using one of the built in keywords like free, delete, or delete[ ]. Other languages like Java and .NET use garbage collection to automatically delete memory from the heap, without the programmer having to do anything..

What can go wrong with the stack and the heap?

If the stack runs out of memory, then this is called a stack overflow – and could cause the program to crash. The heap could have the problem of fragmentation, which occurs when the available memory on the heap is being stored as noncontiguous (or disconnected) blocks – because used blocks of memory are in between the unused memory blocks. When excessive fragmentation occurs, allocating new memory may be impossible because of the fact that even though there is enough memory for the desired allocation, there may not be enough memory in one big block for the desired amount of memory.

Which one should I use – the stack or the heap?

For people new to programming, it’s probably a good idea to use the stack since it’s easier.
Because the stack is small, you would want to use it when you know exactly how much memory you will need for your data, or if you know the size of your data is very small. It’s better to use the heap when you know that you will need a lot of memory for your data, or you just are not sure how much memory you will need (like with a dynamic array).

堆栈 & Stack and Heap的更多相关文章

  1. C# 堆栈和堆 Heap & Stack

    首先堆栈和堆(托管堆)都在进程的虚拟内存中.(在32位处理器上每个进程的虚拟内存为4GB) 堆栈stack 堆栈中存储值类型. 堆栈实际上是向下填充,即由高内存地址指向低内存地址填充. 堆栈的工作方式 ...

  2. java中堆栈(stack)和堆(heap)(还在问静态变量放哪里,局部变量放哪里,静态区在哪里.....进来)

    (1)内存分配的策略 按照编译原理的观点,程序运行时的内存分配有三种策略,分别是静态的,栈式的,和堆式的. 静态存储分配是指在编译时就能确定每个数据目标在运行时刻的存储空间需求,因而在编 译时就可以给 ...

  3. java中堆栈(stack)和堆(heap)

    原文地址:http://blog.csdn.net/jerryao/article/details/874101 1.内存分配策略 按照编译原理的观点,程序运行时的内存分配有三种策略,分别是静态的,栈 ...

  4. 3.2 java中堆栈(stack)和堆(heap)(还在问静态变量放哪里,局部变量放哪里,静态区在哪里.....进来)

    (1)内存分配的策略 按照编译原理的观点,程序运行时的内存分配有三种策略,分别是静态的,栈式的,和堆式的. 静态存储分配是指在编译时就能确定每个数据目标在运行时刻的存储空间需求,因而在编 译时就可以给 ...

  5. JVM的stack和heap,JVM内存模型,垃圾回收策略,分代收集,增量收集

    (转自:http://my.oschina.net/u/436879/blog/85478) 在JVM中,内存分为两个部分,Stack(栈)和Heap(堆),这里,我们从JVM的内存管理原理的角度来认 ...

  6. js in depth: event loop & micro-task, macro-task & stack, queue, heap & thread, process

    js in depth: event loop & micro-task, macro-task & stack, queue, heap & thread, process ...

  7. 【转】JVM运行原理及JVM中的Stack和Heap的实现过程

    来自: http://blog.csdn.net//u011067360/article/details/46047521 Java语言写的源程序通过Java编译器,编译成与平台无关的‘字节码程序’( ...

  8. 图解.NET Stack和Heap的本质区别

    现在越来越觉得对.NET基本概念的理解和掌握对于提升编程水平的重要性,先从.NET的 Stack(栈)和Heap(堆)说起,计算机的内存可以分为代码块内存,stack内存和heap内存.代码块内存是在 ...

  9. JVM运行原理及Stack和Heap的实现过程

    Java语言写的源程序通过Java编译器,编译成与平台无关的‘字节码程序’(.class文件,也就是0,1二进制程序),然后在OS之上的Java解释器中解释执行,而JVM是java的核心和基础,在ja ...

随机推荐

  1. 微信公众平台入门开发教程.Net(C#)框架

    一.序言 一直在想第一次写博客,应该写点什么好?正好最近在研究微信公众平台开发,索性就记录下,分享下自己的心得,也分享下本人简单模仿asp.net运行机制所写的通用的微信公众平台开发.Net(c#)框 ...

  2. WebApi传参总动员(填坑)

    本以为系列文章已经Over,突然记起来前面留了个大坑还没填,真是自己给自己挖坑. 这个坑就是: (body 只能被读取一次)Only one thing can read the body MVC和W ...

  3. 重新想象 Windows 8 Store Apps (38) - 契约: Search Contract

    [源码下载] 重新想象 Windows 8 Store Apps (38) - 契约: Search Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 ...

  4. springMVC全局Exception异常处理SimpleMappingExceptionResolver

    继承了SimpleMappingExceptionResolver 贴上代码 /** * 对controller异常进行全局处理 * 区分了对普通请求和ajax请求的异常处理,普通请求返回到配置的er ...

  5. JS 面向对象 编程设计

    面向对象的语言有一个标志,即拥有类的概念,抽象实例对象的公共属性与方法,基于类可以创建任意多个实例对象,一般具有封装.继承.多态的特性!但JS中对象与纯面向对象语言中的对象是不同的,ECMA标准定义J ...

  6. javascript中的defer是什么?

    今天看到stackoverflow上的这样一个问题(问题链接),大概是说用jQuery获取不到元素,这是我们刚开始接触javascript常常会碰到的问题,回答者列举了4中方法去解决获取不到元素的问题 ...

  7. COMMIT WORK AND WAIT 是在WAIT什么

    wait 还是不wait,这是个问题.       这是同步更新还是异步更新的问题:如果是只commit work,是异步更新,触发注册在当前SAP LUW中所有数据更新动作,数据更新动作由SAP的更 ...

  8. SharePoint 2013 使用查阅项实现联动下拉框

    SharePoint列表使用中,经常会用到下拉框,而有些特殊的需求,会用到联动的下拉框,在SharePoint中默认没有这样的字段,所以如果实现,我们需要自己想办法. 这里,我们介绍如何使用JQuer ...

  9. R语言学习笔记:字符串处理

    想在R语言中生成一个图形文件的文件名,前缀是fitbit,后面跟上月份,再加上".jpg",先不百度,试了试其它语言的类似语法,没一个可行的: C#中:"fitbit&q ...

  10. mac os x使用Git简易入门教程

    具体如下: 1, 首先要了解什么是Git. 简而言之,Git是一个分布式的代码版本管理工具.类似的常用工具还有SVN,CVS. 概念了解参见:http://baike.baidu.com/subvie ...