<ul>
<li>What are the stack and heap?</li>
<li>Where are they located physically in a computer's memory?</li>
<li>To what extent are they controlled by the OS or language run-time?</li>
<li>What is their scope?</li>
<li>What determines their sizes?</li>
<li>What makes one faster?</li>
</ul>

[{'answer_id': 79936, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 11, 'selected': False, 'text': '<p><strong>Stack:</strong></p>\n\n<ul>\n<li>Stored in computer RAM just like the heap.</li>\n<li>Variables created on the stack will go out of scope and are automatically deallocated.</li>\n<li>Much faster to allocate in comparison to variables on the heap.</li>\n<li>Implemented with an actual stack data structure.</li>\n<li>Stores local data, return addresses, used for parameter passing.</li>\n<li>Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).</li>\n<li>Data created on the stack can be used without pointers.</li>\n<li>You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.</li>\n<li>Usually has a maximum size already determined when your program starts.</li>\n</ul>\n\n<p><strong>Heap:</strong></p>\n\n<ul>\n<li>Stored in computer RAM just like the stack.</li>\n<li>In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with <code>delete</code>, <code>delete[]</code>, or <code>free</code>.</li>\n<li>Slower to allocate in comparison to variables on the stack.</li>\n<li>Used on demand to allocate a block of data for use by the program.</li>\n<li>Can have fragmentation when there are a lot of allocations and deallocations.</li>\n<li>In C++ or C, data created on the heap will be pointed to by pointers and allocated with <code>new</code> or <code>malloc</code> respectively.</li>\n<li>Can have allocation failures if too big of a buffer is requested to be allocated.</li>\n<li>You would use the heap if you don\'t know exactly how much data you will need at run time or if you need to allocate a lot of data.</li>\n<li>Responsible for memory leaks.</li>\n</ul>\n\n<p><strong>Example:</strong></p>\n\n<pre class="lang-cpp prettyprint-override"><code>int foo()\n{\n  char *pBuffer; //&lt;--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).\n  bool b = true; // Allocated on the stack.\n  if(b)\n  {\n    //Create 500 bytes on the stack\n    char buffer[500];\n\n    //Create 500 bytes on the heap\n    pBuffer = new char[500];\n\n   }//&lt;-- buffer is deallocated here, pBuffer is not\n}//&lt;--- oops there\'s a memory leak, I should have called delete[] pBuffer;\n</code></pre>\n'}, {'answer_id': 79988, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 8, 'selected': False, 'text': '<p><strong>The Stack</strong>\nWhen you call a function the arguments to that function plus some other overhead is put on the stack. Some info (such as where to go on return) is also stored there.\nWhen you declare a variable inside your function, that variable is also allocated on the stack. </p>\n\n<p>Deallocating the stack is pretty simple because you always deallocate in the reverse order in which you allocate. Stack stuff is added as you enter functions, the corresponding data is removed as you exit them. This means that you tend to stay within a small region of the stack unless you call lots of functions that call lots of other functions (or create a recursive solution).</p>\n\n<p><strong>The Heap</strong>\nThe heap is a generic name for where you put the data that you create on the fly. If you don\'t know how many spaceships your program is going to create, you are likely to use the new (or malloc or equivalent) operator to create each spaceship. This allocation is going to stick around for a while, so it is likely we will free things in a different order than we created them. </p>\n\n<p>Thus, the heap is far more complex, because there end up being regions of memory that are unused interleaved with chunks that are - memory gets fragmented. Finding free memory of the size you need is a difficult problem. This is why the heap should be avoided (though it is still often used).</p>\n\n<p><strong>Implementation</strong>\nImplementation of both the stack and heap is usually down to the runtime / OS. Often games and other applications that are performance critical create their own memory solutions that grab a large chunk of memory from the heap and then dish it out internally to avoid relying on the OS for memory. </p>\n\n<p>This is only practical if your memory usage is quite different from the norm - i.e for games where you load a level in one huge operation and can chuck the whole lot away in another huge operation.</p>\n\n<p><strong>Physical location in memory</strong>\nThis is less relevant than you think because of a technology called <a href="http://en.wikipedia.org/wiki/Virtual_memory" rel="noreferrer">Virtual Memory</a> which makes your program think that you have access to a certain address where the physical data is somewhere else (even on the hard disc!). The addresses you get for the stack are in increasing order as your call tree gets deeper. The addresses for the heap are un-predictable (i.e implimentation specific) and frankly not important.</p>\n'}, {'answer_id': 79997, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 7, 'selected': False, 'text': "<p>The stack is a portion of memory that can be manipulated via several key assembly language instructions, such as 'pop' (remove and return a value from the stack) and 'push' (push a value to the stack), but also call (call a subroutine - this pushes the address to return to the stack) and return (return from a subroutine - this pops the address off of the stack and jumps to it).  It's the region of memory below the stack pointer register, which can be set as needed.  The stack is also used for passing arguments to subroutines, and also for preserving the values in registers before calling subroutines.</p>\n\n<p>The heap is a portion of memory that is given to an application by the operating system, typically through a syscall like malloc.  On modern OSes this memory is a set of pages that only the calling process has access to.</p>\n\n<p>The size of the stack is determined at runtime, and generally does not grow after the program launches.  In a C program, the stack needs to be large enough to hold every variable declared within each function.  The heap will grow dynamically as needed, but the OS is ultimately making the call (it will often grow the heap by more than the value requested by malloc, so that at least some future mallocs won't need to go back to the kernel to get more memory.  This behavior is often customizable)</p>\n\n<p>Because you've allocated the stack before launching the program, you never need to malloc before you can use the stack, so that's a slight advantage there.  In practice, it's very hard to predict what will be fast and what will be slow in modern operating systems that have virtual memory subsystems, because how the pages are implemented and where they are stored is an implementation detail.  </p>\n"}, {'answer_id': 80094, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 7, 'selected': False, 'text': '<p>Others have answered the broad strokes pretty well, so I\'ll throw in a few details.</p>\n\n<ol>\n<li><p>Stack and heap need not be singular. A common situation in which you have more than one stack is if you have more than one thread in a process.  In this case each thread has its own stack. You can also have more than one heap, for example some DLL configurations can result in different DLLs allocating from different heaps, which is why it\'s generally a bad idea to release memory allocated by a different library.</p></li>\n<li><p>In C you can get the benefit of variable length allocation through the use of <a href="https://www.freebsd.org/cgi/man.cgi?alloca" rel="noreferrer">alloca</a>, which allocates on the stack, as opposed to alloc, which allocates on the heap. This memory won\'t survive your return statement, but it\'s useful for a scratch buffer.</p></li>\n<li><p>Making a huge temporary buffer on Windows that you don\'t use much of is not free. This is because the compiler will generate a stack probe loop that is called every time your function is entered to make sure the stack exists (because Windows uses a single guard page at the end of your stack to detect when it needs to grow the stack. If you access memory more than one page off the end of the stack you will crash). Example:</p></li>\n</ol>\n\n<pre class="lang-cpp prettyprint-override"><code>void myfunction()\n{\n   char big[10000000];\n   // Do something that only uses for first 1K of big 99% of the time.\n}\n</code></pre>\n'}, {'answer_id': 80113, 'author': 'Jeff Hill', 'author_id': 14742, 'author_profile': 'https://Stackoverflow.com/users/14742', 'pm_score': 14, 'selected': True, 'text': '<p>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 (last in first out) 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.</p>\n<p>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; there are many custom heap allocators available to tune heap performance for different usage patterns.</p>\n<p>Each thread gets a stack, while there\'s typically only one heap for the application (although it isn\'t uncommon to have multiple heaps for different types of allocation).</p>\n<p>To answer your questions directly:</p>\n<blockquote>\n<p><em>To what extent are they controlled by the OS or language runtime?</em></p>\n</blockquote>\n<p>The OS allocates the stack for each system-level thread when the thread is created.  Typically the OS is called by the language runtime to allocate the heap for the application.</p>\n<blockquote>\n<p><em>What is their scope?</em></p>\n</blockquote>\n<p>The stack is attached to a thread, so when the thread exits the stack is reclaimed.  The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.</p>\n<blockquote>\n<p><em>What determines the size of each of them?</em></p>\n</blockquote>\n<p>The size of the stack is set when a thread is created.  The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).</p>\n<blockquote>\n<p><em>What makes one faster?</em></p>\n</blockquote>\n<p>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 deallocation.  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. Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be - typically - synchronized with &quot;all&quot; other heap accesses in the program.</p>\n<p>A clear demonstration:\n<img src="https://i.stack.imgur.com/i6k0Z.png" alt="" />\n<br/><sub>Image source: <a href="http://vikashazrati.wordpress.com/2007/10/01/quicktip-java-basics-stack-and-heap/" rel="noreferrer">vikashazrati.wordpress.com</a></sub></p>\n'}, {'answer_id': 80142, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': '<p>I think many other people have given you mostly correct answers on this matter.</p>\n\n<p>One detail that has been missed, however, is that the "heap" should in fact probably be called the "free store".  The reason for this distinction is that the original free store was implemented with a data structure known as a "binomial heap."  For that reason, allocating from early implementations of malloc()/free() was allocation from a heap.  However, in this modern day, most free stores are implemented with very elaborate data structures that are not binomial heaps.</p>\n'}, {'answer_id': 80740, 'author': 'bk1e', 'author_id': 8090, 'author_profile': 'https://Stackoverflow.com/users/8090', 'pm_score': 7, 'selected': False, 'text': '<p>Others have directly answered your question, but when trying to understand the stack and the heap, I think it is helpful to consider the memory layout of a traditional UNIX process (without threads and <code>mmap()</code>-based allocators). The <a href="https://www.memorymanagement.org/glossary/b.html#term-brk" rel="nofollow noreferrer">Memory Management Glossary</a> web page has a diagram of this memory layout.</p>\n<p>The stack and heap are traditionally located at opposite ends of the process\'s virtual address space. The stack grows automatically when accessed, up to a size set by the kernel (which can be adjusted with <code>setrlimit(RLIMIT_STACK, ...)</code>). The heap grows when the memory allocator invokes the <code>brk()</code> or <code>sbrk()</code> system call, mapping more pages of physical memory into the process\'s virtual address space.</p>\n<p>In systems without virtual memory, such as some embedded systems, the same basic layout often applies, except the stack and heap are fixed in size. However, in other embedded systems (such as those based on Microchip PIC microcontrollers), the program stack is a separate block of memory that is not addressable by data movement instructions, and can only be modified or read indirectly through program flow instructions (call, return, etc.). Other architectures, such as Intel Itanium processors, have <a href="https://devblogs.microsoft.com/oldnewthing/20050421-28/?p=35833" rel="nofollow noreferrer">multiple stacks</a>. In this sense, the stack is an element of the CPU architecture.</p>\n'}, {'answer_id': 662454, 'author': 'thomasrutter', 'author_id': 53212, 'author_profile': 'https://Stackoverflow.com/users/53212', 'pm_score': 11, 'selected': False, 'text': '<p>The most important point is that heap and stack are generic terms for ways in which memory can be allocated.  They can be implemented in many different ways, and the terms apply to the basic concepts.</p>\n\n<ul>\n<li><p>In a stack of items, items sit one on top of the other in the order they were placed there, and you can only remove the top one (without toppling the whole thing over).</p>\n\n<p><img src="https://i.stack.imgur.com/ZLzMV.jpg" alt="Stack like a stack of papers"></p>\n\n<p>The simplicity of a stack is that you do not need to maintain a table containing a record of each section of allocated memory; the only state information you need is a single pointer to the end of the stack.  To allocate and de-allocate, you just increment and decrement that single pointer.  Note: a stack can sometimes be implemented to start at the top of a section of memory and extend downwards rather than growing upwards.</p></li>\n<li><p>In a heap, there is no particular order to the way items are placed.  You can reach in and remove items in any order because there is no clear \'top\' item.</p>\n\n<p><img src="https://i.stack.imgur.com/kINqo.jpg" alt="Heap like a heap of licorice allsorts"></p>\n\n<p>Heap allocation requires maintaining a full record of what memory is allocated and what isn\'t, as well as some overhead maintenance to reduce fragmentation, find contiguous memory segments big enough to fit the requested size, and so on.  Memory can be deallocated at any time leaving free space.  Sometimes a memory allocator will perform maintenance tasks such as defragmenting memory by moving allocated memory around, or garbage collecting - identifying at runtime when memory is no longer in scope and deallocating it. </p></li>\n</ul>\n\n<p>These images should do a fairly good job of describing the two ways of allocating and freeing memory in a stack and a heap.  Yum!</p>\n\n<ul>\n<li><p>To what extent are they controlled by the OS or language runtime?</p>\n\n<p>As mentioned, heap and stack are general terms, and can be implemented in many ways.  Computer programs typically have a stack called a <a href="http://en.wikipedia.org/wiki/Call_stack" rel="noreferrer">call stack</a> which stores information relevant to the current function such as a pointer to whichever function it was called from, and any local variables.  Because functions call other functions and then return, the stack grows and shrinks to hold information from the functions further down the call stack.  A program doesn\'t really have runtime control over it; it\'s determined by the programming language, OS and even the system architecture.</p>\n\n<p>A heap is a general term used for any memory that is allocated dynamically and randomly; i.e. out of order.  The memory is typically allocated by the OS, with the application calling API functions to do this allocation.  There is a fair bit of overhead required in managing dynamically allocated memory, which is usually handled by the runtime code of the programming language or environment used.</p></li>\n<li><p>What is their scope?</p>\n\n<p>The call stack is such a low level concept that it doesn\'t relate to \'scope\' in the sense of programming.  If you disassemble some code you\'ll see relative pointer style references to portions of the stack, but as far as a higher level language is concerned, the language imposes its own rules of scope.  One important aspect of a stack, however, is that once a function returns, anything local to that function is immediately freed from the stack.  That works the way you\'d expect it to work given how your programming languages work.  In a heap, it\'s also difficult to define.  The scope is whatever is exposed by the OS, but your programming language probably adds its rules about what a "scope" is in your application.  The processor architecture and the OS use virtual addressing, which the processor translates to physical addresses and there are page faults, etc.  They keep track of what pages belong to which applications.  You never really need to worry about this, though, because you just use whatever method your programming language uses to allocate and free memory, and check for errors (if the allocation/freeing fails for any reason).</p></li>\n<li><p>What determines the size of each of them?</p>\n\n<p>Again, it depends on the language, compiler, operating system and architecture.  A stack is usually pre-allocated, because by definition it must be contiguous memory.  The language compiler or the OS determine its size.  You don\'t store huge chunks of data on the stack, so it\'ll be big enough that it should never be fully used, except in cases of unwanted endless recursion (hence, "stack overflow") or other unusual programming decisions.</p>\n\n<p>A heap is a general term for anything that can be dynamically allocated.  Depending on which way you look at it, it is constantly changing size.  In modern processors and operating systems the exact way it works is very abstracted anyway, so you don\'t normally need to worry much about how it works deep down, except that (in languages where it lets you) you mustn\'t use memory that you haven\'t allocated yet or memory that you have freed.</p></li>\n<li><p>What makes one faster?</p>\n\n<p>The stack is faster because all free memory is always contiguous.  No list needs to be maintained of all the segments of free memory, just a single pointer to the current top of the stack.  Compilers usually store this pointer in a special, fast <a href="http://en.wikipedia.org/wiki/Stack_register" rel="noreferrer">register</a> for this purpose.  What\'s more, subsequent operations on a stack are usually concentrated within very nearby areas of memory, which at a very low level is good for optimization by the processor on-die caches.</p></li>\n</ul>\n'}, {'answer_id': 662570, 'author': 'T.E.D.', 'author_id': 29639, 'author_profile': 'https://Stackoverflow.com/users/29639', 'pm_score': 7, 'selected': False, 'text': '<p>Simply, the stack is where local variables get created. Also, every time you call a subroutine the program counter (pointer to the next machine instruction) and any important registers, and sometimes the parameters get pushed on the stack. Then any local variables inside the subroutine are pushed onto the stack (and used from there). When the subroutine finishes, that stuff all gets popped back off the stack. The PC and register data gets and put back where it was as it is popped, so your program can go on its merry way.</p>\n\n<p>The heap is the area of memory dynamic memory allocations are made out of (explicit "new" or "allocate" calls). It is a special data structure that can keep track of blocks of memory of varying sizes and their allocation status.</p>\n\n<p>In "classic" systems RAM was laid out such that the stack pointer started out at the bottom of memory, the heap pointer started out at the top, and they grew towards each other. If they overlap, you are out of RAM. That doesn\'t work with modern multi-threaded OSes though. Every thread has to have its own stack, and those can get created dynamicly.</p>\n'}, {'answer_id': 662783, 'author': 'Peter', 'author_id': 80094, 'author_profile': 'https://Stackoverflow.com/users/80094', 'pm_score': 7, 'selected': False, 'text': '<p>You can do some interesting things with the stack.  For instance, you have functions like <a href="http://everything2.com/title/alloca%2528%2529" rel="noreferrer">alloca</a> (assuming you can get past the copious warnings concerning its use), which is a form of malloc that specifically uses the stack, not the heap, for memory.</p>\n\n<p>That said, stack-based memory errors are some of the worst I\'ve experienced.  If you use heap memory, and you overstep the bounds of your allocated block, you have a decent chance of triggering a segment fault.  (Not 100%: your block may be incidentally contiguous with another that you have previously allocated.)  But since variables created on the stack are always contiguous with each other, writing out of bounds can change the value of another variable.  I have learned that whenever I feel that my program has stopped obeying the laws of logic, it is probably buffer overflow.</p>\n'}, {'answer_id': 707970, 'author': 'devXen', 'author_id': 50021, 'author_profile': 'https://Stackoverflow.com/users/50021', 'pm_score': 6, 'selected': False, 'text': '<p>From WikiAnwser.</p>\n\n<h3>Stack</h3>\n\n<p>When a function or a method calls another function which in turns calls another function, etc., the execution of all those functions remains suspended until the very last function returns its value.</p>\n\n<p>This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.</p>\n\n<p>The stack is important to consider in exception handling and thread executions.</p>\n\n<h3>Heap</h3>\n\n<p>The heap is simply the memory used by programs to store variables.\nElement of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.</p>\n'}, {'answer_id': 1213360, 'author': 'Martin Liversage', 'author_id': 98607, 'author_profile': 'https://Stackoverflow.com/users/98607', 'pm_score': 10, 'selected': False, 'text': '<p>(I have moved this answer from another question that was more or less a dupe of this one.)</p>\n<p>The answer to your question is implementation specific and may vary across compilers and processor architectures. However, here is a simplified explanation.</p>\n<ul>\n<li>Both the stack and the heap are memory areas allocated from the underlying operating system (often virtual memory that is mapped to physical memory on demand).</li>\n<li>In a multi-threaded environment each thread will have its own completely independent stack but they will share the heap. Concurrent access has to be controlled on the heap and is not possible on the stack.</li>\n</ul>\n<h2>The heap</h2>\n<ul>\n<li>The heap contains a linked list of used and free blocks. New allocations on the heap (by <code>new</code> or <code>malloc</code>) are satisfied by creating a suitable block from one of the free blocks. This requires updating the list of blocks on the heap. This <em>meta information</em> about the blocks on the heap is also stored on the heap often in a small area just in front of every block.</li>\n<li>As the heap grows new blocks are often allocated from lower addresses towards higher addresses. Thus you can think of the heap as a <em>heap</em> of memory blocks that grows in size as memory is allocated. If the heap is too small for an allocation the size can often be increased by acquiring more memory from the underlying operating system.</li>\n<li>Allocating and deallocating many small blocks may leave the heap in a state where there are a lot of small free blocks interspersed between the used blocks. A request to allocate a large block may fail because none of the free blocks are large enough to satisfy the allocation request even though the combined size of the free blocks may be large enough. This is called <em>heap fragmentation</em>.</li>\n<li>When a used block that is adjacent to a free block is deallocated the new free block may be merged with the adjacent free block to create a larger free block effectively reducing the fragmentation of the heap.</li>\n</ul>\n<p><img src="https://i.stack.imgur.com/0Obi0.png" alt="The heap" /></p>\n<h2>The stack</h2>\n<ul>\n<li>The stack often works in close tandem with a special register on the CPU named the <em>stack pointer</em>. Initially the stack pointer points to the top of the stack (the highest address on the stack).</li>\n<li>The CPU has special instructions for <em>pushing</em> values onto the stack and <em>popping</em> them off the stack. Each <em>push</em> stores the value at the current location of the stack pointer and decreases the stack pointer. A <em>pop</em> retrieves the value pointed to by the stack pointer and then increases the stack pointer (don\'t be confused by the fact that <em>adding</em> a value to the stack <em>decreases</em> the stack pointer and <em>removing</em> a value <em>increases</em> it. Remember that the stack grows to the bottom). The values stored and retrieved are the values of the CPU registers.</li>\n<li>If a function has parameters, these are pushed onto the stack before the call to the function. The code in the function is then able to navigate up the stack from the current stack pointer to locate these values.</li>\n<li>When a function is called the CPU uses special instructions that push the current <em>instruction pointer</em> onto the stack, i.e. the address of the code executing on the stack. The CPU then jumps to the function by setting the instruction pointer to the address of the function called. Later, when the function returns, the old instruction pointer is popped off the stack and execution resumes at the code just after the call to the function.</li>\n<li>When a function is entered, the stack pointer is decreased to allocate more space on the stack for local (automatic) variables. If the function has one local 32 bit variable four bytes are set aside on the stack. When the function returns, the stack pointer is moved back to free the allocated area.</li>\n<li>Nesting function calls work like a charm. Each new call will allocate function parameters, the return address and space for local variables and these <em>activation records</em> can be stacked for nested calls and will unwind in the correct way when the functions return.</li>\n<li>As the stack is a limited block of memory, you can cause a <em>stack overflow</em> by calling too many nested functions and/or allocating too much space for local variables. Often the memory area used for the stack is set up in such a way that writing below the bottom (the lowest address) of the stack will trigger a trap or exception in the CPU. This exceptional condition can then be caught by the runtime and converted into some kind of stack overflow exception.</li>\n</ul>\n<p><img src="https://i.stack.imgur.com/9UshP.png" alt="The stack" /></p>\n<blockquote>\n<p>Can a function be allocated on the heap instead of a stack?</p>\n</blockquote>\n<p>No, activation records for functions (i.e. local or automatic variables) are allocated on the stack that is used not only to store these variables, but also to keep track of nested function calls.</p>\n<p>How the heap is managed is really up to the runtime environment. C uses <code>malloc</code> and C++ uses <code>new</code>, but many other languages have garbage collection.</p>\n<p>However, the stack is a more low-level feature closely tied to the processor architecture. Growing the heap when there is not enough space isn\'t too hard since it can be implemented in the library call that handles the heap. However, growing the stack is often impossible as the stack overflow only is discovered when it is too late; and shutting down the thread of execution is the only viable option.</p>\n'}, {'answer_id': 13308092, 'author': 'Snowcrash', 'author_id': 343204, 'author_profile': 'https://Stackoverflow.com/users/343204', 'pm_score': 9, 'selected': False, 'text': '<p>In the following C# code</p>\n<pre class="lang-cs prettyprint-override"><code>public void Method1()\n{\n    int i = 4;\n    int y = 2;\n    class1 cls1 = new class1();\n}\n</code></pre>\n<p>Here\'s how the memory is managed</p>\n<p><img src="https://i.stack.imgur.com/NS0k7.jpg" alt="Picture of variables on the stack" /></p>\n<p><code>Local Variables</code> that only need to last as long as the function invocation go in the stack. The heap is used for variables whose lifetime we don\'t really know up front but we expect them to last a while. In most languages it\'s critical that we know at compile time how large a variable is if we want to store it on the stack.</p>\n<p>Objects (which vary in size as we update them) go on the heap because we don\'t know at creation time how long they are going to last. In many languages the heap is garbage collected to find objects (such as the cls1 object) that no longer have any references.</p>\n<p>In Java, most objects go directly into the heap. In languages like C / C++, structs and classes can often remain on the stack when you\'re not dealing with pointers.</p>\n<p>More information can be found here:</p>\n<p><a href="https://web.archive.org/web/20200216082556/http://timmurphy.org/2010/08/11/the-difference-between-stack-and-heap-memory-allocation/" rel="noreferrer">The difference between stack and heap memory allocation «  timmurphy.org</a></p>\n<p>and here:</p>\n<p><a href="https://root.cern.ch/root/htmldoc/guides/users-guide/ALittleC++.html#creating-objects-on-the-stack-and-heap" rel="noreferrer">Creating Objects on the Stack and Heap</a></p>\n<p>This article is the source of picture above: <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types#Stack%20and%20Heap" rel="noreferrer">Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing - CodeProject</a></p>\n<p>but be aware it may contain some inaccuracies.</p>\n'}, {'answer_id': 13326916, 'author': 'davec', 'author_id': 1763801, 'author_profile': 'https://Stackoverflow.com/users/1763801', 'pm_score': 8, 'selected': False, 'text': '<p>Other answers just avoid explaining what static allocation means. So I will explain the three main forms of allocation and how they usually relate to the heap, stack, and data segment below. I also will show some examples in both C/C++ and Python to help people understand.</p>\n<p>&quot;Static&quot; (AKA statically allocated) variables are not allocated on the stack. Do not assume so - many people do only because &quot;static&quot; sounds a lot like &quot;stack&quot;. They actually exist in neither the stack nor the heap. They are part of what\'s called the <a href="http://en.wikipedia.org/wiki/Data_segment" rel="noreferrer">data segment</a>.</p>\n<p>However, it is generally better to consider &quot;<strong>scope</strong>&quot; and &quot;<strong>lifetime</strong>&quot; rather than &quot;stack&quot; and &quot;heap&quot;.</p>\n<p>Scope refers to what parts of the code can access a variable. Generally we think of <strong>local scope</strong> (can only be accessed by the current function) versus <strong>global scope</strong> (can be accessed anywhere) although scope can get much more complex.</p>\n<p>Lifetime refers to when a variable is allocated and deallocated during program execution. Usually we think of <strong>static allocation</strong> (variable will persist through the entire duration of the program, making it useful for storing the same information across several function calls) versus <strong>automatic allocation</strong> (variable only persists during a single call to a function, making it useful for storing information that is only used during your function and can be discarded once you are done) versus <strong>dynamic allocation</strong> (variables whose duration is defined at runtime, instead of compile time like static or automatic).</p>\n<p>Although most compilers and interpreters implement this behavior similarly in terms of using stacks, heaps, etc, a compiler may sometimes break these conventions if it wants as long as behavior is correct. For instance, due to optimization a local variable may only exist in a register or be removed entirely, even though most local variables exist in the stack. As has been pointed out in a few comments, you are free to implement a compiler that doesn\'t even use a stack or a heap, but instead some other storage mechanisms (rarely done, since stacks and heaps are great for this).</p>\n<p>I will provide some simple annotated C code to illustrate all of this. The best way to learn is to run a program under a debugger and watch the behavior. If you prefer to read python, skip to the end of the answer :)</p>\n<pre class="lang-cpp prettyprint-override"><code>// Statically allocated in the data segment when the program/DLL is first loaded\n// Deallocated when the program/DLL exits\n// scope - can be accessed from anywhere in the code\nint someGlobalVariable;\n\n// Statically allocated in the data segment when the program is first loaded\n// Deallocated when the program/DLL exits\n// scope - can be accessed from anywhere in this particular code file\nstatic int someStaticVariable;\n\n// &quot;someArgument&quot; is allocated on the stack each time MyFunction is called\n// &quot;someArgument&quot; is deallocated when MyFunction returns\n// scope - can be accessed only within MyFunction()\nvoid MyFunction(int someArgument) {\n\n    // Statically allocated in the data segment when the program is first loaded\n    // Deallocated when the program/DLL exits\n    // scope - can be accessed only within MyFunction()\n    static int someLocalStaticVariable;\n\n    // Allocated on the stack each time MyFunction is called\n    // Deallocated when MyFunction returns\n    // scope - can be accessed only within MyFunction()\n    int someLocalVariable;\n\n    // A *pointer* is allocated on the stack each time MyFunction is called\n    // This pointer is deallocated when MyFunction returns\n    // scope - the pointer can be accessed only within MyFunction()\n    int* someDynamicVariable;\n\n    // This line causes space for an integer to be allocated in the heap\n    // when this line is executed. Note this is not at the beginning of\n    // the call to MyFunction(), like the automatic variables\n    // scope - only code within MyFunction() can access this space\n    // *through this particular variable*.\n    // However, if you pass the address somewhere else, that code\n    // can access it too\n    someDynamicVariable = new int;\n\n\n    // This line deallocates the space for the integer in the heap.\n    // If we did not write it, the memory would be &quot;leaked&quot;.\n    // Note a fundamental difference between the stack and heap\n    // the heap must be managed. The stack is managed for us.\n    delete someDynamicVariable;\n\n    // In other cases, instead of deallocating this heap space you\n    // might store the address somewhere more permanent to use later.\n    // Some languages even take care of deallocation for you... but\n    // always it needs to be taken care of at runtime by some mechanism.\n\n    // When the function returns, someArgument, someLocalVariable\n    // and the pointer someDynamicVariable are deallocated.\n    // The space pointed to by someDynamicVariable was already\n    // deallocated prior to returning.\n    return;\n}\n\n// Note that someGlobalVariable, someStaticVariable and\n// someLocalStaticVariable continue to exist, and are not\n// deallocated until the program exits.\n</code></pre>\n<p>A particularly poignant example of why it\'s important to distinguish between lifetime and scope is that a variable can have local scope but static lifetime - for instance, &quot;someLocalStaticVariable&quot; in the code sample above. Such variables can make our common but informal naming habits very confusing. For instance when we say &quot;<em>local</em>&quot; we usually mean &quot;<em>locally scoped automatically allocated variable</em>&quot; and when we say global we usually mean &quot;<em>globally scoped statically allocated variable</em>&quot;. Unfortunately when it comes to things like &quot;<em>file scoped statically allocated variables</em>&quot; many people just say... &quot;<em>huh???</em>&quot;.</p>\n<p>Some of the syntax choices in C/C++ exacerbate this problem - for instance many people think global variables are not &quot;static&quot; because of the syntax shown below.</p>\n<pre class="lang-cpp prettyprint-override"><code>int var1; // Has global scope and static allocation\nstatic int var2; // Has file scope and static allocation\n\nint main() {return 0;}\n</code></pre>\n<p>Note that putting the keyword &quot;static&quot; in the declaration above prevents var2 from having global scope. Nevertheless, the global var1 has static allocation. This is not intuitive! For this reason, I try to never use the word &quot;static&quot; when describing scope, and instead say something like &quot;file&quot; or &quot;file limited&quot; scope. However many people use the phrase &quot;static&quot; or &quot;static scope&quot; to describe a variable that can only be accessed from one code file. In the context of lifetime, &quot;static&quot; <em>always</em> means the variable is allocated at program start and deallocated when program exits.</p>\n<p>Some people think of these concepts as C/C++ specific. They are not. For instance, the Python sample below illustrates all three types of allocation (there are some subtle differences possible in interpreted languages that I won\'t get into here).</p>\n<pre class="lang-py prettyprint-override"><code>from datetime import datetime\n\nclass Animal:\n    _FavoriteFood = \'Undefined\' # _FavoriteFood is statically allocated\n\n    def PetAnimal(self):\n        curTime = datetime.time(datetime.now()) # curTime is automatically allocatedion\n        print(&quot;Thank you for petting me. But it\'s &quot; + str(curTime) + &quot;, you should feed me. My favorite food is &quot; + self._FavoriteFood)\n\nclass Cat(Animal):\n    _FavoriteFood = \'tuna\' # Note since we override, Cat class has its own statically allocated _FavoriteFood variable, different from Animal\'s\n\nclass Dog(Animal):\n    _FavoriteFood = \'steak\' # Likewise, the Dog class gets its own static variable. Important to note - this one static variable is shared among all instances of Dog, hence it is not dynamic!\n\n\nif __name__ == &quot;__main__&quot;:\n    whiskers = Cat() # Dynamically allocated\n    fido = Dog() # Dynamically allocated\n    rinTinTin = Dog() # Dynamically allocated\n\n    whiskers.PetAnimal()\n    fido.PetAnimal()\n    rinTinTin.PetAnimal()\n\n    Dog._FavoriteFood = \'milkbones\'\n    whiskers.PetAnimal()\n    fido.PetAnimal()\n    rinTinTin.PetAnimal()\n\n# Output is:\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is tuna\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is steak\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is steak\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is tuna\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is milkbones\n# Thank you for petting me. But it\'s 13:05:02.256000, you should feed me. My favorite food is milkbones\n</code></pre>\n'}, {'answer_id': 21449421, 'author': 'unknown', 'author_id': 1152398, 'author_profile': 'https://Stackoverflow.com/users/1152398', 'pm_score': 6, 'selected': False, 'text': "<p><strong>Stack</strong></p>\n\n<ul>\n<li>Very fast access</li>\n<li>Don't have to explicitly de-allocate variables</li>\n<li>Space is managed efficiently by CPU, memory will not become fragmented</li>\n<li>Local variables only</li>\n<li>Limit on stack size (OS-dependent)</li>\n<li>Variables cannot be resized</li>\n</ul>\n\n<p><strong>Heap</strong></p>\n\n<ul>\n<li>Variables can be accessed globally</li>\n<li>No limit on memory size</li>\n<li>(Relatively) slower access</li>\n<li>No guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed</li>\n<li>You must manage memory (you're in charge of allocating and freeing variables)</li>\n<li>Variables can be resized using realloc()</li>\n</ul>\n"}, {'answer_id': 24171266, 'author': 'Shreyos Adikari', 'author_id': 838841, 'author_profile': 'https://Stackoverflow.com/users/838841', 'pm_score': 7, 'selected': False, 'text': '<p><strong>What is a stack?</strong></p>\n<p>A stack is a pile of objects, typically one that is neatly arranged.</p>\n<p><a href="https://i.stack.imgur.com/GTa97.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/GTa97.jpg" alt="Enter image description here" /></a></p>\n<blockquote>\n<blockquote>\n<p>Stacks in computing architectures are regions of memory where data is added or removed in a last-in-first-out manner. <br/>\nIn a multi-threaded application, each thread will have its own stack.</p>\n</blockquote>\n</blockquote>\n<p><strong>What is a heap?</strong></p>\n<p>A heap is an untidy collection of things piled up haphazardly.</p>\n<p><a href="https://i.stack.imgur.com/rz43z.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/rz43z.jpg" alt="Enter image description here" /></a></p>\n<blockquote>\n<blockquote>\n<p>In computing architectures the heap is an area of dynamically-allocated memory that is managed automatically by the operating system or the memory manager library. <br/>\nMemory on the heap is allocated, deallocated, and resized regularly during program execution, and this can lead to a problem called fragmentation. <br/>\nFragmentation occurs when memory objects are allocated with small spaces in between that are too small to hold additional memory objects. <br/>\nThe net result is a percentage of the heap space that is not usable for further memory allocations.</p>\n</blockquote>\n</blockquote>\n<p><strong>Both together</strong></p>\n<blockquote>\n<blockquote>\n<p>In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap. <br/>\nBecause 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.</p>\n</blockquote>\n</blockquote>\n<p><strong>Which is faster – the stack or the heap? And why?</strong></p>\n<blockquote>\n<blockquote>\n<p>The stack is much faster than the heap. <br/>\nThis is because of the way that memory is allocated on the stack. <br/>\nAllocating memory on the stack is as simple as moving the stack pointer up.</p>\n</blockquote>\n</blockquote>\n<p>For people new to programming, it’s probably a good idea to use the stack since it’s easier. <br/>\nBecause 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. <br/>\nIt’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).</p>\n<h3>Java Memory Model</h3>\n<p><a href="https://i.stack.imgur.com/yZK6t.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yZK6t.png" alt="Enter image description here" /></a></p>\n<p>The stack is the area of memory where local variables (including method parameters) are stored. When it comes to object variables, these are merely references (pointers) to the actual objects on the heap.<br>\nEvery time an object is instantiated, a chunk of heap memory is set aside to hold the data (state) of that object. Since objects can contain other objects, some of this data can in fact hold references to those nested objects.</p>\n'}, {'answer_id': 28801420, 'author': 'shakurov', 'author_id': 2212026, 'author_profile': 'https://Stackoverflow.com/users/2212026', 'pm_score': 5, 'selected': False, 'text': '<p>Since some answers went nitpicking, I\'m going to contribute my mite.</p>\n\n<p>Surprisingly, no one has mentioned that multiple (i.e. not related to the number of running OS-level threads) call stacks are to be found not only in exotic languages (PostScript) or platforms (Intel Itanium), but also in <a href="http://en.wikipedia.org/wiki/Fiber_(computer_science)" rel="noreferrer"><em>fibers</em></a>, <a href="http://en.wikipedia.org/wiki/Green_threads" rel="noreferrer"><em>green threads</em></a> and some implementations of <a href="http://en.wikipedia.org/wiki/Coroutine" rel="noreferrer"><em>coroutines</em></a>.</p>\n\n<p>Fibers, green threads and coroutines are in many ways similar, which leads to much confusion.  The difference between fibers and green threads is that the former use cooperative multitasking, while the latter may feature either cooperative or preemptive one (or even both). For the distinction between fibers and coroutines, see <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4024.pdf" rel="noreferrer">here</a>.</p>\n\n<p>In any case, the purpose of both fibers, green threads and coroutines is having multiple functions executing concurrently, but <strong>not</strong> in parallel (see <a href="https://stackoverflow.com/questions/1050222/concurrency-vs-parallelism-what-is-the-difference">this SO question</a> for the distinction) within a single OS-level thread, transferring control back and forth from one another in an organized fashion.</p>\n\n<p>When using fibers, green threads or coroutines, you <em>usually</em> have a separate stack per function. (Technically, not just a stack but a whole context of execution is per function. Most importantly, CPU registers.) For every thread there\'re as many stacks as there\'re concurrently running functions, and the thread is switching between executing each function according to the logic of your program. When a function runs to its end, its stack is destroyed. So, <strong>the number and lifetimes of stacks</strong> are dynamic and <strong>are not determined by the number of OS-level threads!</strong></p>\n\n<p>Note that I said "<em>usually</em> have a separate stack per function". There\'re both <em>stackful</em> and <em>stackless</em> implementations of couroutines. Most notable stackful C++ implementations are <a href="http://www.boost.org/doc/libs/1_53_0/libs/coroutine/doc/html/index.html" rel="noreferrer">Boost.Coroutine</a> and <a href="https://msdn.microsoft.com/en-us/library/dd492418.aspx" rel="noreferrer">Microsoft PPL</a>\'s <code>async/await</code>. (However, C++\'s <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4134.pdf" rel="noreferrer">resumable functions</a> (a.k.a. "<code>async</code> and <code>await</code>"), which were proposed to C++17, are likely to use stackless coroutines.)</p>\n\n<p>Fibers proposal to the C++ standard library is forthcoming. Also, there\'re some third-party <a href="https://stackoverflow.com/questions/1285714/lightweight-portable-c-fibers-mit-license">libraries</a>. Green threads are extremely popular in languages like Python and Ruby.</p>\n'}, {'answer_id': 29309167, 'author': 'jlettvin', 'author_id': 1363592, 'author_profile': 'https://Stackoverflow.com/users/1363592', 'pm_score': 5, 'selected': False, 'text': '<p>In the 1980s, UNIX propagated like bunnies with big companies rolling their own.\nExxon had one as did dozens of brand names lost to history.\nHow memory was laid out was at the discretion of the many implementors.</p>\n\n<p>A typical C program was laid out flat in memory with\nan opportunity to increase by changing the brk() value.\nTypically, the HEAP was just below this brk value\nand increasing brk increased the amount of available heap.</p>\n\n<p>The single STACK was typically an area below HEAP which was a tract of memory\ncontaining nothing of value until the top of the next fixed block of memory.\nThis next block was often CODE which could be overwritten by stack data\nin one of the famous hacks of its era.</p>\n\n<p>One typical memory block was BSS (a block of zero values)\nwhich was accidentally not zeroed in one manufacturer\'s offering.\nAnother was DATA containing initialized values, including strings and numbers.\nA third was CODE containing CRT (C runtime), main, functions, and libraries.</p>\n\n<p>The advent of virtual memory in UNIX changes many of the constraints.\nThere is no objective reason why these blocks need be contiguous,\nor fixed in size, or ordered a particular way now.\nOf course, before UNIX was Multics which didn\'t suffer from these constraints.\nHere is a schematic showing one of the memory layouts of that era.</p>\n\n<p><img src="https://i.stack.imgur.com/eeefv.png" alt="A typical 1980s style UNIX C program memory layout"></p>\n'}, {'answer_id': 34337843, 'author': 'Maxim Akristiniy', 'author_id': 4176813, 'author_profile': 'https://Stackoverflow.com/users/4176813', 'pm_score': 5, 'selected': False, 'text': '<p>A couple of cents: I think, it will be good to draw memory graphical and more simple:</p>\n\n<p><a href="https://i.stack.imgur.com/nlb7A.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nlb7A.jpg" alt="This is my vision of process memory construction with simplification for more easy understanding wht happening"></a></p>\n\n<p><br>\nArrows - show where grow stack and heap, process stack size have limit, defined in OS, thread stack size limits by parameters in thread create API usually. Heap usually limiting by process maximum virtual memory size, for 32 bit 2-4&nbsp;GB for example.</p>\n\n<p>So simple way: process heap is general for process and all threads inside, using for memory allocation in common case with something like <strong>malloc()</strong>.</p>\n\n<p>Stack is quick memory for store in common case function return pointers and variables, processed as parameters in function call, local function variables.</p>\n'}, {'answer_id': 36982240, 'author': 'Abrar Jahin', 'author_id': 2193439, 'author_profile': 'https://Stackoverflow.com/users/2193439', 'pm_score': 6, 'selected': False, 'text': '<h2>In Short</h2>\n\n<p>A stack is used for static memory allocation and a heap for dynamic memory allocation, both stored in the computer\'s RAM.</p>\n\n<hr>\n\n<h2>In Detail</h2>\n\n<p><strong>The Stack</strong></p>\n\n<p>The stack is a "LIFO" (last in, first out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.</p>\n\n<p>The advantage of using the stack to store variables, is that memory is managed for you. You don\'t have to allocate memory by hand, or free it once you don\'t need it any more. What\'s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.</p>\n\n<p>More can be found <strong><a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)" rel="noreferrer">here</a></strong>.</p>\n\n<hr>\n\n<p><strong>The Heap</strong></p>\n\n<p>The heap is a region of your computer\'s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free() to deallocate that memory once you don\'t need it any more.</p>\n\n<p>If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won\'t be available to other processes). As we will see in the debugging section, there is a tool called <a href="http://en.wikipedia.org/wiki/Valgrind" rel="noreferrer">Valgrind</a> that can help you detect memory leaks.</p>\n\n<p>Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.</p>\n\n<p>Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.</p>\n\n<p>More can be found <strong><a href="https://en.wikipedia.org/wiki/Memory_management" rel="noreferrer">here</a></strong>.</p>\n\n<hr>\n\n<p>Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function, etc., the execution of all those functions remains suspended until the very last function returns its value. 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.</p>\n\n<p>Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. Elements of the heap have no dependencies with each other and can always be accessed randomly at any time. 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.</p>\n\n<p><a href="https://i.stack.imgur.com/KdBPf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KdBPf.png" alt="Enter image description here"></a></p>\n\n<p>You can use the stack if you know exactly how much data you need to allocate before compile time, and it is not too big. You can use the heap if you don\'t know exactly how much data you will need at runtime or if you need to allocate a lot of data.</p>\n\n<p>In a multi-threaded situation each thread will have its own completely independent stack, but they will share the heap. The stack is thread specific and the heap is application specific. The stack is important to consider in exception handling and thread executions.</p>\n\n<p>Each thread gets a stack, while there\'s typically only one heap for the application (although it isn\'t uncommon to have multiple heaps for different types of allocation).</p>\n\n<p><a href="https://i.stack.imgur.com/J0teH.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/J0teH.gif" alt="Enter image description here"></a></p>\n\n<p>At run-time, if the application needs more heap, it can allocate memory from free memory and if the stack needs memory, it can allocate memory from free memory allocated memory for the application.</p>\n\n<p>Even, more detail is given <a href="http://net-informations.com/faq/net/stack-heap.htm" rel="noreferrer"><strong>here</strong></a> and <a href="http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html" rel="noreferrer"><strong>here</strong></a>.</p>\n\n<hr>\n\n<p>Now come to <strong>your question\'s answers</strong>.</p>\n\n<blockquote>\n  <p><strong>To what extent are they controlled by the OS or language runtime?</strong></p>\n</blockquote>\n\n<p>The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application.</p>\n\n<p>More can be found <strong><a href="https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap/80113#80113">here</a></strong>.</p>\n\n<blockquote>\n  <p><strong>What is their scope?</strong></p>\n</blockquote>\n\n<p>Already given in top.</p>\n\n<blockquote>\n  <p>"You can use the stack if you know exactly how much data you need to allocate before compile time, and it is not too big. You can use the heap if you don\'t know exactly how much data you will need at runtime or if you need to allocate a lot of data."</p>\n</blockquote>\n\n<p>More can be found in <a href="https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c">here</a>.</p>\n\n<blockquote>\n  <p><strong>What determines the size of each of them?</strong></p>\n</blockquote>\n\n<p>The size of the stack is set by <a href="https://en.wikipedia.org/wiki/Operating_system" rel="noreferrer">OS</a> when a thread is created. The size of the heap is set on application startup, but it can grow as space is needed (the allocator requests more memory from the operating system).</p>\n\n<blockquote>\n  <p><strong>What makes one faster?</strong></p>\n</blockquote>\n\n<p>Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.</p>\n\n<p>Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.</p>\n\n<p>Details can be found from <strong><a href="https://stackoverflow.com/questions/161053/which-is-faster-stack-allocation-or-heap-allocation">here</a></strong>.</p>\n'}, {'answer_id': 45170558, 'author': 'Alireza', 'author_id': 5423108, 'author_profile': 'https://Stackoverflow.com/users/5423108', 'pm_score': 6, 'selected': False, 'text': '<p><strong>OK,</strong> simply and in short words, they mean <strong>ordered</strong> and <strong>not ordered</strong>...!</p>\n\n<p><strong>Stack</strong>: In stack items, things get on the top of each-other, means gonna be faster and more efficient to be processed!... </p>\n\n<p>So there is always an index to point the specific item, also processing gonna be faster, there is relationship between the items as well!...</p>\n\n<p><strong>Heap</strong>: No order, processing gonna be slower and values are messed up together with no specific order or index... there are random and there is no relationship between them... so execution and usage time could be vary...</p>\n\n<p>I also create the image below to show how they may look like:</p>\n\n<p><a href="https://i.stack.imgur.com/9c2VH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9c2VH.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 45361888, 'author': 'ingconti', 'author_id': 927333, 'author_profile': 'https://Stackoverflow.com/users/927333', 'pm_score': 3, 'selected': False, 'text': "<p>A lot of answers are correct as concepts, but we must note that a stack is needed by the hardware (i.e. microprocessor) to allow calling subroutines (CALL in assembly language..). (OOP guys will call it <em>methods</em>)</p>\n\n<p>On the stack you save return addresses and call → push / ret → pop is managed directly in hardware.</p>\n\n<p>You can use the stack to pass parameters.. even if it is slower than using registers (would a microprocessor guru say or a good 1980s BIOS book...)</p>\n\n<ul>\n<li>Without stack <strong>no</strong> microprocessor can work. (we can't imagine a program, even in assembly language, without subroutines/functions)</li>\n<li>Without the heap it can. (An assembly language program can work without, as the heap is a OS concept, as malloc, that is a OS/Lib call.</li>\n</ul>\n\n<p>Stack usage is faster as:</p>\n\n<ul>\n<li>Is hardware, and even push/pop are very efficient.</li>\n<li>malloc requires entering kernel mode, use lock/semaphore (or other synchronization primitives) executing some code and manage some structures needed to keep track of allocation.</li>\n</ul>\n"}, {'answer_id': 46225186, 'author': 'Yousha Aleayoub', 'author_id': 1429432, 'author_profile': 'https://Stackoverflow.com/users/1429432', 'pm_score': 5, 'selected': False, 'text': '<p><strong>stack</strong>, <strong>heap</strong> and <strong>data</strong> of each process in virtual memory:</p>\n\n<p><a href="https://bayanbox.ir/view/581244719208138556/virtual-memory.jpg" rel="noreferrer"><img src="https://bayanbox.ir/view/581244719208138556/virtual-memory.jpg" alt="stack, heap and static data"></a></p>\n'}, {'answer_id': 47314733, 'author': 'pkthapa', 'author_id': 1163286, 'author_profile': 'https://Stackoverflow.com/users/1163286', 'pm_score': 5, 'selected': False, 'text': '<p>I have something to share, although the major points are already covered.</p>\n\n<p><strong>Stack</strong>  </p>\n\n<ul>\n<li>Very fast access.</li>\n<li>Stored in RAM.</li>\n<li>Function calls are loaded here along with the local variables and function parameters passed.</li>\n<li>Space is freed automatically when program goes out of a scope.</li>\n<li>Stored in sequential memory.</li>\n</ul>\n\n<p><strong>Heap</strong></p>\n\n<ul>\n<li>Slow access comparatively to Stack.</li>\n<li>Stored in RAM.</li>\n<li>Dynamically created variables are stored here, which later requires freeing the allocated memory after use.</li>\n<li>Stored wherever memory allocation is done, accessed by pointer always.</li>\n</ul>\n\n<p><strong>Interesting note:</strong></p>\n\n<ul>\n<li>Should the function calls had been stored in heap, it would had resulted in 2 messy points:  \n\n<ol>\n<li>Due to sequential storage in stack, execution is faster. Storage in heap would have resulted in huge time consumption thus making the whole program execute slower.</li>\n<li>If functions were stored in heap (messy storage pointed by pointer), there would have been no way to return to the caller address back (which stack gives due to sequential storage in memory).</li>\n</ol></li>\n</ul>\n'}, {'answer_id': 54777773, 'author': 'ar18', 'author_id': 6147643, 'author_profile': 'https://Stackoverflow.com/users/6147643', 'pm_score': 4, 'selected': False, 'text': '<p>Wow! So many answers and I don\'t think one of them got it right...</p>\n\n<p>1) Where and what are they (physically in a real computer\'s memory)?</p>\n\n<p>The stack is memory that begins as the highest memory address allocated to your program image, and it then decrease in value from there. It is reserved for called function parameters and for all temporary variables used in functions.</p>\n\n<p>There are two heaps: public and private.</p>\n\n<p>The private heap begins on a 16-byte boundary (for 64-bit programs) or a 8-byte boundary (for 32-bit programs) after the last byte of code in your program, and then increases in value from there. It is also called the default heap.</p>\n\n<p>If the private heap gets too large it will overlap the stack area, as will the stack overlap the heap if it gets too big. Because the stack starts at a higher address and works its way down to lower address, with proper hacking you can get make the stack so large that it will overrun the private heap area and overlap the code area. The trick then is to overlap enough of the code area that you can hook into the code. It\'s a little tricky to do and you risk a program crash, but it\'s easy and very effective.</p>\n\n<p>The public heap resides in it\'s own memory space outside of your program image space. It is this memory that will be siphoned off onto the hard disk if memory resources get scarce.</p>\n\n<p>2) To what extent are they controlled by the OS or language runtime?</p>\n\n<p>The stack is controlled by the programmer, the private heap is managed by the OS, and the public heap is not controlled by anyone because it is an OS service -- you make requests and either they are granted or denied.</p>\n\n<p>2b) What is their scope?</p>\n\n<p>They are all global to the program, but their contents can be private, public, or global.</p>\n\n<p>2c) What determines the size of each of them?</p>\n\n<p>The size of the stack and the private heap are determined by your compiler runtime options. The public heap is initialized at runtime using a size parameter.</p>\n\n<p>2d) What makes one faster?</p>\n\n<p>They are not designed to be fast, they are designed to be useful. How the programmer utilizes them determines whether they are "fast" or "slow"</p>\n\n<p>REF:</p>\n\n<p><a href="https://norasandler.com/2019/02/18/Write-a-Compiler-10.html" rel="noreferrer">https://norasandler.com/2019/02/18/Write-a-Compiler-10.html</a></p>\n\n<p><a href="https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-getprocessheap" rel="noreferrer">https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-getprocessheap</a></p>\n\n<p><a href="https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-heapcreate" rel="noreferrer">https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-heapcreate</a></p>\n'}, {'answer_id': 60795592, 'author': 'nCardot', 'author_id': 8888320, 'author_profile': 'https://Stackoverflow.com/users/8888320', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>The stack is essentially an easy-to-access memory that simply manages its items \n  as a - well - stack. Only <strong>items for which the size is known in advance can go onto the stack</strong>. This is the case for numbers, strings, booleans.</p>\n  \n  <p>The <strong>heap is a memory for items of which you can’t predetermine the\n  exact size and structure</strong>. Since objects and arrays can be mutated and\n  change at runtime, they have to go into the heap.</p>\n</blockquote>\n\n<p>Source: <a href="https://academind.com/learn/javascript/reference-vs-primitive-values/" rel="nofollow noreferrer">Academind</a></p>\n'}, {'answer_id': 61124687, 'author': 'aquagremlin', 'author_id': 3418334, 'author_profile': 'https://Stackoverflow.com/users/3418334', 'pm_score': 0, 'selected': False, 'text': '<p>Thank you for a really good discussion but as a real noob I wonder where instructions are kept? In the BEGINNING scientists were deciding between two architectures (von NEUMANN where everything is considered DATA and HARVARD where an area of memory was reserved for instructions and another for data). Ultimately, we went with the von Neumann design and now everything is considered \'the same\'. This made it hard for me when I was learning assembly \n<a href="https://www.cs.virginia.edu/~evans/cs216/guides/x86.html" rel="nofollow noreferrer">https://www.cs.virginia.edu/~evans/cs216/guides/x86.html</a>\nbecause they talk about registers and stack pointers.  </p>\n\n<p>Everything above talks about DATA. My guess is that since an instruction is a defined thing with a specific memory footprint, it would go on the stack and so all \'those\' registers discussed in assembly are on the stack. Of course then came object oriented programming with instructions and data comingled into a structure that was dynamic so now instructions would be kept on the heap as well?</p>\n'}, {'answer_id': 62739706, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>CPU stack and heap are physically related to how CPU and registers works with memory, how machine-assembly language works, not high-level languages themselves, even if these languages can decide little things.</p>\n<p>All modern CPUs work with the &quot;same&quot; microprocessor theory: they are all based on what\'s called &quot;registers&quot; and some are for &quot;stack&quot; to gain performance. All CPUs have stack registers since the beginning and they had been always here, way of talking, as I know. Assembly languages are the same since the beginning, despite variations... up to Microsoft and its Intermediate Language (IL) that changed the paradigm to have a OO virtual machine assembly language. So we\'ll be able to have some CLI/CIL CPU in the future (one project of MS).</p>\n<p>CPUs have stack registers to speed up memories access, but they are limited compared to the use of others registers to get full access to all the available memory for the processus. It why we talked about stack and heap allocations.</p>\n<p>In summary, and in general, the heap is hudge and slow and is for &quot;global&quot; instances and objects content, as the stack is little and fast and for &quot;local&quot; variables and references (hidden pointers to forget to manage them).</p>\n<p>So when we use the new keyword in a method, the reference (an int) is created in the stack, but the object and all its content (value-types as well as objects) is created in the heap, if I remember. But local elementary value-types and arrays are created in the stack.</p>\n<p>The difference in memory access is at the cells referencing level: addressing the heap, the overall memory of the process, requires more complexity in terms of handling CPU registers, than the stack which is &quot;more&quot; locally in terms of addressing because the CPU stack register is used as base address, if I remember.</p>\n<p>It is why when we have very long or infinite recurse calls or loops, we got stack overflow quickly, without freezing the system on modern computers...</p>\n<p><a href="https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/" rel="nofollow noreferrer">C# Heap(ing) Vs Stack(ing) In .NET</a></p>\n<p><a href="https://www.guru99.com/stack-vs-heap.html" rel="nofollow noreferrer">Stack vs Heap: Know the Difference </a></p>\n<p><a href="https://stackoverflow.com/questions/33562199/static-class-memory-allocation-where-it-is-stored-c-sharp">Static class memory allocation where it is stored C#</a></p>\n<p><a href="https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap">What and where are the stack and heap?</a></p>\n<p><a href="https://en.wikipedia.org/wiki/Memory_management" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Memory_management</a></p>\n<p><a href="https://en.wikipedia.org/wiki/Stack_register" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Stack_register</a></p>\n<p>Assembly language resources:</p>\n<p><a href="https://www.tutorialspoint.com/assembly_programming/index.htm" rel="nofollow noreferrer">Assembly Programming Tutorial</a></p>\n<p><a href="https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html" rel="nofollow noreferrer">Intel® 64 and IA-32 Architectures Software Developer Manuals</a></p>\n'}, {'answer_id': 69523039, 'author': 'anshkun', 'author_id': 3484350, 'author_profile': 'https://Stackoverflow.com/users/3484350', 'pm_score': 0, 'selected': False, 'text': '<p>When a process is created then after loading code and data OS setup heap start just after data ends and stack to top of address space based on architecture</p>\n<p>When more heap is required OS will allocate dynamically and heap chunk is always virtually contiguous</p>\n<p>Please see <code>brk()</code>, <code>sbrk()</code> and <code>alloca()</code> system call in linux</p>\n'}, {'answer_id': 70050292, 'author': 'A. Hendry', 'author_id': 8748308, 'author_profile': 'https://Stackoverflow.com/users/8748308', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n<p>Where and what are they (physically in a real computer's memory)?</p>\n</blockquote>\n<p><strong>ANSWER:</strong> <strong>Both are in RAM.</strong></p>\n<p><strong>ASIDE:</strong></p>\n<p><em>RAM is like a desk and HDDs/SSDs (permanent storage) are like bookshelves. To read anything, you must have a book open on your desk, and you can only have as many books open as fit on your desk. To get a book, you pull it from your bookshelf and open it on your desk. To return a book, you close the book on your desk and return it to its bookshelf.</em></p>\n<p><em>Stack and heap are names we give to two ways compilers store different kinds of data in the same place (i.e. in RAM).</em></p>\n<blockquote>\n<p>What is their scope?<br />\nWhat determines the size of each of them?<br />\nWhat makes one faster?</p>\n</blockquote>\n<p><strong>ANSWER:</strong></p>\n<ol>\n<li><p><strong>The stack is for static (fixed size) data</strong></p>\n<p>a. <em>At compile time, the compiler reads the variable types used in your code.</em></p>\n<p>i. It allocates a fixed amount of memory for these variables.<br />\nii. This size of this memory cannot grow.</p>\n<p>b. <em>The memory is contiguous (a single block), so access is</em> <strong>sometimes</strong> <em>faster than the heap</em></p>\n<p>c. <em>An object placed on the stack that grows in memory during runtime beyond the size of the stack causes a</em> <strong>stack overflow error</strong></p>\n</li>\n<li><p><strong>The heap is for dynamic (changing size) data</strong></p>\n<p>a. <em>The amount of memory is limited only by the amount of empty space available in RAM</em><br />\ni. The amount used can grow or shrink as needed at runtime</p>\n<p>b. <em>Since items are allocated on the heap by finding empty space wherever it exists in RAM, data is not always in a contiguous section, which</em> <strong>sometimes</strong> <em>makes access slower than the stack</em></p>\n<p>c. <em>Programmers manually put items on the heap with the <code>new</code> keyword and MUST manually deallocate this memory when they are finished using it.</em><br />\ni. Code that repeatedly allocates new memory without deallocating it when it is no longer needed leads to a <strong>memory leak.</strong></p>\n</li>\n</ol>\n<p><strong>ASIDE:</strong></p>\n<p>The stack and heap were not primarily introduced to improve speed; they were introduced to handle memory overflow. The first concern regarding use of the stack vs. the heap should be whether memory overflow will occur. If an object is intended to grow in size to an unknown amount (like a linked list or an object whose members can hold an arbitrary amount of data), place it on the heap. As far as possible, use the C++ standard library (STL) containers <strong>vector</strong>, <strong>map</strong>, and <strong>list</strong> as they are memory and speed efficient and added to make your life easier (you don't need to worry about memory allocation/deallocation).</p>\n<p>After getting your code to run, if you find it is running unacceptably slow, then go back and refactor your code and see if it can be programmed more efficiently. It may turn out the problem has nothing to do with the stack or heap directly at all (e.g. use an iterative algorithm instead of a recursive one, look at I/O vs. CPU-bound tasks, perhaps add multithreading or multiprocessing).</p>\n<p>I say <em>sometimes</em> slower/faster above because the speed of the program might not have anything to do with items being allocated on the stack or heap.</p>\n<blockquote>\n<p>To what extent are they controlled by the OS or language run-time?</p>\n</blockquote>\n<p><strong>ANSWER:</strong></p>\n<ul>\n<li><p><strong>The stack size is determined at compile time by the compiler.</strong></p>\n</li>\n<li><p><strong>The heap size varies during runtime.</strong> (<em>The heap works with the OS during runtime to allocate memory.</em>)</p>\n</li>\n</ul>\n<p><strong>ASIDE:</strong></p>\n<p>Below is a little more about control and compile-time vs. runtime operations.</p>\n<p>Each computer has a unique <strong>instruction set architecture (ISA)</strong>, which are its hardware commands (e.g. &quot;MOVE&quot;, &quot;JUMP&quot;, &quot;ADD&quot;, etc.).</p>\n<ul>\n<li><p>An OS is nothing more than a resource manager (controls how/when/ and where to use memory, processors, devices, and information).</p>\n</li>\n<li><p>The ISA of the OS is called the <strong>bare machine</strong> and the remaining commands are called the <strong>extended machine</strong>. The <strong>kernel</strong> is the first layer of the extended machine. It controls things like</p>\n<ul>\n<li>determining what tasks get to use a processor (the scheduler),</li>\n<li>how much memory or how many hardware registers to allocate to a task (the dispatcher), and</li>\n<li>the order in which tasks should be performed (the traffic controller).</li>\n</ul>\n</li>\n<li><p>When we say &quot;compiler&quot;, we generally mean the compiler, assembler, and linker together</p>\n<ul>\n<li>The compiler turns source code into assembly language and passes it to the assembler,</li>\n<li>The assembler turns the assembly language into machine code (ISA commands), and passes it to the linker</li>\n<li>The linker takes all machine code (possibly generated from multiple source files) and combines it into one program.</li>\n</ul>\n</li>\n<li><p>The machine code gets passed to the kernel when executed, which determines when it should run and take control, but the machine code itself contains ISA commands for requesting files, requesting memory, etc. So the code issues ISA commands, but everything has to pass by the kernel.</p>\n</li>\n</ul>\n"}, {'answer_id': 73615900, 'author': 'Shivprasad Koirala', 'author_id': 993672, 'author_profile': 'https://Stackoverflow.com/users/993672', 'pm_score': 1, 'selected': False, 'text': '<p>Below are answers but I would surely recommend you to watch this video where stack, heap inside memory addresses are  shown , how stack memory addresses are contiguous are shown  which gives a fair idea on how stack and heaps work. <a href="https://www.youtube.com/watch?v=7O4JPdKjc30" rel="nofollow noreferrer">https://www.youtube.com/watch?v=7O4JPdKjc30</a></p>\n<p><strong>What are the stack and heap?</strong></p>\n<p>Stack and Heap are memory types allocated to an application while its running. In Stack local primitive types, structures,object reference pointers are stored while in heap actual object data is stored. *** Heap can also store primitive types / structures only if they are part of the object.</p>\n<p><strong>Where are they located physically in a computer\'s memory?</strong></p>\n<p>They are allocated on RAM ( Random Access Memory)</p>\n<p><strong>To what extent are they controlled by the OS or language run-time?</strong></p>\n<p>Everything is controlled by OS.</p>\n<p><strong>What is their scope?</strong></p>\n<p>Stack memory is cleared as soon the function , method is executed. While heap is cleared later by garbage collector. Garbage collector runs in his own mood. So even though the function has finised execution its very much possible that GC will come little later and give the memory back to OS.</p>\n<p><strong>What determines their sizes?</strong></p>\n<p>Primitive data  types are fixed size depending on datatype for example int is 32 bit , long 64 and so on. But when it comes to objects there is no fixed size , it can be huge image  object or it can be a  small object with two 3 properties.</p>\n<p><strong>What makes one faster?</strong></p>\n<p>Stack is surely faster as the memory addresses are contiguous  so its very easy to allocate and deallocate. While heaps are allocated in random addresses so allocating and deallocating both is tedious task. Especially deallocating memory is most resource intensive and that\'s what garbage collector does.</p>\n<p>Think for while is it easy find a book in stack or in heap.</p>\n'}]
['https://Stackoverflow.com/questions/79923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13161/']