http://www.programmerinterview.com/index.php/data-structures/difference-between-stack-and-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 overflow occurs. 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 – thesmall details 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 deletedmanually 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 unusedmemory 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).

What’s the difference between a stack and a heap?的更多相关文章

  1. java - Stack栈和Heap堆的区别

    首先分清楚Stack,Heap的中文翻译:Stack—栈,Heap—堆.         在中文里,Stack可以翻译为“堆栈”,所以我直接查找了计算机术语里面堆和栈开头的词语:        堆存储 ...

  2. JAVA Stack栈和Heap堆的区别(转)

          首先分清楚Stack,Heap的中文翻译:Stack—栈,Heap—堆.         在中文里,Stack可以翻译为“堆栈”,所以我直接查找了计算机术语里面堆和栈开头的词语:      ...

  3. 栈(stack)和堆(heap)

    栈(stack)和堆(heap), Java程序在运行时都要开辟空间,任何软件在运行时都要在内存中开辟空间,Java虚拟机运行时也是要开辟空间的.JVM运行时在内存中开辟一片内存区域,启动时在自己的内 ...

  4. 如何给女朋友讲明白:Java 中 Stack(栈) 与 Heap(堆)

    背景 Java 中 Stack(栈) 与 Heap(堆) 是面试中被经常问到的一个话题. 有没有对 Java 中 Stack(栈) 与 Heap(堆) 烂熟于心的童鞋,请举手!!!(怎么没人举手-) ...

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

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

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

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

  7. Java再学习——栈(stack)和堆(heap)

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

  8. stack对象与heap对象

    从高地址到低地址,分别是stack,heap,static object,stack地址往下增长,heap地址往上增长.只要记住:stack栈顶地址反而小,就知道往下增长了. 禁止产生堆对象 1.产生 ...

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

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

随机推荐

  1. js map()初步学习

    //array.map(callback,thisObject?),callback需要有return值 //map:'映射' 被映射成新的数组  eg1: let data = [3,4,2]; l ...

  2. python入门练习之如何连接数据库

    !/usr/bin/python -- coding: UTF-8 -- author = 'luke' from sqlalchemy import create_engine from sqlal ...

  3. Sql数据库收缩 语句特别快

    数据库在收缩的时候..使用菜单 >> 任务 >> 收缩 >> 文件 >> 数据,  特别慢..还会报错失败.. 但使用脚本 USE [dbName] G ...

  4. Asp.net MVC中repository和service的区别

    在Asp.net MVC controller的底层,常常有提到repository和service layer, 好像都是逻辑相关的层,那么它们到底是什么区别呢? 简单的说: repository就 ...

  5. npm全局安装和局部文件安装区别

    全局安装往往是安装一个工具,他不是安装在一个文件夹下,而是安装在某个全局环境下,如目前我的安装路径是: C:\Users\cvter\AppData\Roaming\npm 在这里,我们可以看到所有全 ...

  6. PHP面向对象的基本思路

    第一步:识别对象 ——任何实体都可以被识别为一个对象 第二步:识别对象的属性 ——对象里面存储的数据被识别为属性 ——对于不同的业务逻辑,关注的数据不同,独享里面存储的属性也不同 第三步:识别对象的行 ...

  7. LINUX安装UNZIP

    安装完linux ,发现没有UNZIP,没办法,重新安装. 1.获取unzip源码 sudo wget http://downloads.sourceforge.net/infozip/unzip55 ...

  8. Jenkins~powershell+cmd发布nuget包包

    nuget包也要自动化部署了,想想确实挺好,在实施过程中我们要解决的问题有版本自动控制,nuget自动打包,nuget自动上传到服务端等. 一 参数化构建 二 环境变量的k/v参数,存储类库的初始版本 ...

  9. php.ini配置max_execution_time和FPM配置request_terminate_timeout

    PHP限定脚本执行时长的方式有几种,下面说下php.ini中的max_execution_time和php-fpm.conf中的request_terminate_timeout 1. php.ini ...

  10. FastReport打印table

    经过验证是对的. table第一行添加标题,也就是拖过来的文本label,第二行开始绑定数据源的字段. 先设计报表的静态部分,再用代码注册数据源,然后设计,添加注册的数据源,绑定字段. var rep ...