What and where are the stack and heap?

Programming language books explain that value types are created on the stack, and reference types are created on the heap, without explaining what these two things are. I haven't read a clear explanation of this. I understand what a stack is, but where and what are they (physically in a real computer's memory)?

  • To what extent are they controlled by the OS or language runtime?
  • What is their scope?
  • What determines the size of each of them?
  • What makes one faster?

memory-management language-agnostic stack heap

share|improve this question

edited Apr 24 '15 at 10:49

 

Eilidh

531524

asked Sep 17 '08 at 4:18

 

mattshane

26.1k3104

 
41 

a really good explanation can be found here What’s the difference between a stack and a heap? – Songo Dec 16 '13 at 11:32

114 

This is why having tried assembly language programming is important too, even for high level programmers. You need to know the machine underneath. – Thorbjørn Ravn Andersen Dec 30 '13 at 13:35

25 

@ThorbjørnRavnAndersen I disagree. Given a sufficiently high enough level of abstraction, I don't have to care about whether things are allocated on the heap or the stack any more than you have to care about what specific instructions are generated with a lower level of abstraction. – joneshf Jun 2 '14 at 16:11

37 

@joneshf "sufficiently high level of abstraction" generally results in "slower". A few years back the LMAX disruptor showed that it is possible to do 100k TPS with less than 1ms latency in Java. This is only possible by understanding the physical machine underneath the JVM - you may want to watch infoq.com/presentations/LMAX – Thorbjørn Ravn Andersen Jun 2 '14 at 16:57

24 

@joneshf as a developer, thinking knowing high level things being enough is another word of lazy. – Jackson Tale Jun 11 '14 at 9:17

 |  show 7 more comments

22 Answers 22

active oldest votes

up vote3719down voteaccepted

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.

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.

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).

To answer your questions directly:

To what extent are they controlled by the OS or language runtime?

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.

What is their scope?

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.

What determines the size of each of them?

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).

What makes one faster?

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or 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 "all" other heap accesses in the program.

A clear demonstration:
Image source: vikashazrati.wordpress.com

share|improve this answer

edited May 2 at 12:35

 

Ates Goral

72.2k1698164

answered Sep 17 '08 at 4:52

 

Jeff Hill

38.7k3106

 
12 

I think you should clarify your last statement. According to your reasoning, ONLY allocation is necessarily faster, right? – Joe Philllips Mar 19 '09 at 16:05

3 

To add to my previous statement, if you're going to allocate an object once and keep it throughout the life of your process, it would be better to use a heap, right? – Joe Philllips Mar 19 '09 at 16:07

151 

@Jeff - your answer was superb - I wanted to have this kind of question in a similar way to use as an interview question - then I realised I didn't exactly know the answer myself either! How bad is is that?! And FYI : bookkeeper is the ONLY English word with 3 consecutive double letters ;) – Lee James Nov 13 '12 at 20:19

8 

@shabunc - re bookkeeping, I think you mean doubled letters rather than vowels, and in particular, doubled consecutive letters. :) (possessionlessness has no doubled vowels, for example) – Colin Kershaw Aug 15 '13 at 21:57

5 

Good answer - but I think you should add that while the stack is allocated by the OS when the process starts (assuming the existence of an OS), it is maintained inline by the program. This is another reason the stack is faster, as well - push and pop operations are typically one machine instruction, and modern machines can do at least 3 of them in one cycle, whereas allocating or freeing heap involves calling into OS code. – sqykly Oct 8 '13 at 8:31

 |  show 4 more comments

i.gif?e=eyJhdiI6NDE0LCJhdCI6NCwiYnQiOjAsImNtIjo0MDQyODMsImNoIjoxMTc4LCJjayI6e30sImNyIjoxNDM0MzA2LCJkaSI6ImVmYTA2YTc2NDY0MjQ4NzQ5ZmMyYmU2NGJhMzUzM2Q2IiwiZG0iOjEsImZjIjoxNjQ5MzA2LCJmbCI6MTQ0ODM0MiwiaXAiOiI2MS4xNDQuMjQ4LjE3Iiwia3ciOiJtZW1vcnktbWFuYWdlbWVudCxsYW5ndWFnZS1hZ25vc3RpYyxzdGFjayxoZWFwIiwibnciOjIyLCJwYyI6MCwiZWMiOjAsInByIjoxNjA0LCJydCI6MSwicmYiOiJodHRwczovL3d3dy5iYWlkdS5jb20vbGluaz91cmw9cXY0VGZlTjdlU1JvNVNUVTRUc3dqaUZvazFSdlFweXJYeDRhdUhlV3E5YXc4UHI4RjRtaFZEN01aTUljdUNGR3hPeU4xQ3pUOE1xaFR2bE5xeG5Ta2Jqa1NOajlUdXpfeXk3bDZ4d2tLRW4xZkRBb2RFRUVzdWZLNWJZbElsVkImd2Q9JmVxaWQ9OTNhMjc2OWIwMDAzN2RlNjAwMDAwMDA2NTdiMWEyMWYiLCJzdCI6ODI3NywidWsiOiJ1ZTEtMWE5ZmQzYzg0ZTNjNDlmMDhiMGU0NGU1ZmZkNmU4MGIiLCJ6biI6NDQsInRzIjoxNDcxMjU5MjY0MjkyLCJiZiI6dHJ1ZSwicG4iOiJjbGMtbWxiIiwiZnEiOjB9&s=Yx2OifReYXTRfc2xQfeiNqdVRWQ

up vote1601down vote

Stack:

  • Stored in computer RAM just like the heap.
  • Variables created on the stack will go out of scope and automatically deallocate.
  • Much faster to allocate in comparison to variables on the heap.
  • Implemented with an actual stack data structure.
  • Stores local data, return addresses, used for parameter passing
  • Can have a stack overflow when too much of the stack is used. (mostly from infinite (or too much) recursion, very large allocations)
  • Data created on the stack can be used without pointers.
  • 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.
  • Usually has a maximum size already determined when your program starts

Heap:

  • Stored in computer RAM just like the stack.
  • In C, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[], or free
  • Slower to allocate in comparison to variables on the stack.
  • Used on demand to allocate a block of data for use by the program.
  • Can have fragmentation when there are a lot of allocations and deallocations
  • In C++ data created on the heap will be pointed to by pointers and allocated with new or malloc
  • Can have allocation failures if too big of a buffer is requested to be allocated.
  • You would 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.
  • Responsible for memory leaks

Example:

int foo()
{
  char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
  bool b = true; // Allocated on the stack.
  if(b)
  {
    //Create 500 bytes on the stack
    char buffer[500];

    //Create 500 bytes on the heap
    pBuffer = new char[500];

   }//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;

share|improve this answer

edited Jul 1 at 22:03

 

Max

439

answered Sep 17 '08 at 4:20

 

Brian R. Bondy

193k82465570

 
17 

The pointer pBuffer and the value of b are located on the stack, and are mostly likely allocated at the entrance to the function. Depending on the compiler, buffer may be allocated at the function entrance, as well. – Andy Mar 18 '09 at 22:48

16 

It is a common misconception that the C language, as defined by the C99 language standard (available at open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf ), requires a "stack". In fact, the word 'stack' does not even appear in the standard. This answers statements wrt/ to C's stack usage are true in general, but is in no way required by the language. See knosof.co.uk/cbook/cbook.html for more info, and in particular how C is implemented on odd-ball architectures such as en.wikipedia.org/wiki/Burroughs_large_systems – johne Sep 1 '09 at 4:37

27 

@Brian You should explain why buffer[] and the pBuffer pointer are created on the stack and why pBuffer's data is created on the heap. I think some ppl might be confused by your answer as they might think the program is specifically instructing that memory be allocated on the stack vs heap but this is not the case. Is it because Buffer is a value type whereas pBuffer is a reference type? – Howiecamp Feb 8 '10 at 4:56

48 

-1: The standard does not guarantee that the stack or the heap are in RAM. – Thomas Eding Jun 12 '12 at 0:45

5 

"Responsible for memory leaks" - Heaps are not responsible for memory leaks! Lazy/Forgetful/ex-java coders/coders who dont give a crap are! – Laz Mar 25 '13 at 8:22

 |  show 14 more comments

up vote1044down vote

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.

  • 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).

    Stack like a stack of papers

  • 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.

    Heap like a heap of licorice allsorts

It does a fairly good job of describing the two ways of allocating and freeing memory in a stack and a heap. Yum!

  • To what extent are they controlled by the OS or language runtime?

    As mentioned, heap and stack are general terms, and can be implemented in many ways. Computer programs typically have a stack called a call stack 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.

    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 OS.

  • What is their scope?

    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).

  • What determines the size of each of them?

    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 (more on that in the last paragraph). 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.

    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.

  • What makes one faster?

    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 register 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.

share|improve this answer

edited Aug 28 '14 at 22:50

Boann

26.5k75994

answered Mar 19 '09 at 14:38

 

thomasrutter

65.5k14104137

 
8 

David I don't agree that that is a good image or that "push-down stack" is a good term to illustrate the concept. When you add something to a stack, the other contents of the stack aren't pushed down, they remain where they are. – thomasrutter Aug 13 '12 at 3:40

4 

This answer includes a big mistake. Static variables are not allocated on the stack. See my answer [link] stackoverflow.com/a/13326916/1763801 for clarification. you are equating "automatic" variables with "static" variables, but they are not at all the same – davec Nov 10 '12 at 23:07

9 

Specifically, you say "statically allocated local variables" are allocated on the stack. Actually they are allocated in the data segment. Only automatically allocated variables (which includes most but not all local variables and also things like function parameters passed in by value rather than by reference) are allocated on the stack. – davec Nov 11 '12 at 1:44

3 

I've just realised you're right - in C, static allocation is its own separate thing rather than a term for anything that's not dynamic. I've edited my answer, thanks. – thomasrutter Nov 12 '12 at 0:29

3 

It's not just C. Java, Pascal, Python and many others all have the notions of static versus automatic versus dynamic allocation. Saying "static allocation" means the same thing just about everywhere. In no language does static allocation mean "not dynamic". You want the term "automatic" allocation for what you are describing (i.e. the things on the stack). – davec Nov 12 '12 at 17:16

 |  show 9 more comments

up vote535down vote

(I have moved this answer from another question that was more or less a dupe of this one.)

The answer to your question is implementation specific and may vary across compilers and processor architectures. However, here is a simplified explanation.

  • 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).
  • 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.

The heap

  • The heap contains a linked list of used and free blocks. New allocations on the heap (by new or malloc) are satisfied by creating a suitable block from one of the free blocks. This requires updating list of blocks on the heap. This meta information about the blocks on the heap is also stored on the heap often in a small area just in front of every block.
  • As the heap grows new blocks are often allocated from lower addresses towards higher addresses. Thus you can think of the heap as a heap 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.
  • 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 heap fragmentation.
  • 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.

The heap

The stack

  • The stack often works in close tandem with a special register on the CPU named the stack pointer. Initially the stack pointer points to the top of the stack (the highest address on the stack).
  • The CPU has special instructions for pushing values onto the stack and popping them back from the stack. Each push stores the value at the current location of the stack pointer and decreases the stack pointer. A pop retrieves the value pointed to by the stack pointer and then increases the stack pointer (don't be confused by the fact that adding a value to the stack decreases the stack pointer and removing a value increases it. Remember that the stack grows to the bottom). The values stored and retrieved are the values of the CPU registers.
  • When a function is called the CPU uses special instructions that push the current instruction pointer, 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 from the stack and execution resumes at the code just after the call to the function.
  • 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.
  • 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.
  • Nesting function calls work like a charm. Each new call will allocate function parameters, the return address and space for local variables and these activation records can be stacked for nested calls and will unwind in the correct way when the functions return.
  • As the stack is a limited block of memory, you can cause a stack overflow 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.

The stack

Can a function be allocated on the heap instead of a stack?

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.

How the heap is managed is really up to the runtime environment. C uses malloc and C++ uses new, but many other languages have garbage collection.

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.

share|improve this answer

edited Mar 28 '12 at 23:03

answered Jul 31 '09 at 15:54

 

Martin Liversage

63.9k13123181

 
17 

@Martin - A very good answer/explanation than the more abstract accepted answer. A sample assembly program showing stack pointers/registers being used vis a vis function calls would be more illustrative. – Bikal Gurung Apr 25 '12 at 16:42

   

Every reference type is composition of value types(int, string etc). As it is said, that value types are stored in stack than how does it work when they are part of reference type. – Nps Feb 15 '14 at 10:26

4 

This answer was the best in my opinion, because it helped me understand what a return statement really is and how it relates to this "return address" that I come across every now and then, what it means to push a function onto the stack, and why functions are pushed onto stacks. Great answer! – Alex Mar 19 '14 at 19:59

   

This is the best in my opinion, namely for mentioning that the heap/stack are very implementation specific. The other answers assume a lot of things about the language and the environment/OS. +1 – Qix Nov 29 '14 at 2:00

   

What do you mean "The code in the function is then able to navigate up the stack from the current stack pointer to locate these values." ? Can you elaborate on this please? – Koray Tugay May 3 '15 at 9:36

 |  show 6 more comments

up vote255down vote

In the following C# code

public void Method1()
{
    int i = 4;
    int y = 2;
    class1 cls1 = new class1();
}

Here's how the memory is managed

Picture of variables on the stack

Local Variables 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.

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.

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.

More information can be found here:

The difference between stack and heap memory allocation « timmurphy.org

and here:

Creating Objects on the Stack and Heap

This article is the source of picture above: Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing - CodeProject

but be aware it may contain some inaccuracies.

share|improve this answer

edited Sep 9 '14 at 23:08

 

Tom Leys

12.6k52756

answered Nov 9 '12 at 12:28

 

Snow Crash

20.2k2169113

 
9 

This is incorrect. i and cls are not "static" variables. they are called "local" or "automatic" variables. It is a very important distinction. See [link] stackoverflow.com/a/13326916/1763801 for clarification – davec Nov 10 '12 at 23:05

4 

I did not say they were static variables. I said that int and cls1 are static items. Their memory is statically allocated and therefore they go on the stack. This is in contrast to an object which requires dynamic memory allocation which therefore goes on the heap. – Snow Crash Nov 20 '12 at 14:38

4 

I quote "Static items... go on the stack". This is just flat out wrong. Static items go in the data segment, automatic items go on the stack. – davec Nov 21 '12 at 16:55

4 

Also whoever wrote that codeproject article doesn't know what he is talking about. For instance, he says "primitive ones needs static type memory" which is completely untrue. Nothing stops you from allocating primitives in the heap dynamically, just write something like "int array[] = new int[num]" and voila, primitives allocated dynamically in .NET. That is just one of several inaccuracies. – davec Nov 21 '12 at 17:02

2 

I edited your post because you have made serious technical mistakes about what goes in the stack and heap. – Tom Leys Sep 9 '14 at 23:09

 |  show 6 more comments

up vote132down vote

The Stack When 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. When you declare a variable inside your function, that variable is also allocated on the stack.

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).

The Heap The 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.

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).

Implementation Implementation 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.

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.

Physical location in memory This is less relevant than you think because of a technology called Virtual Memory 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.

share|improve this answer

edited Sep 17 '08 at 4:34

answered Sep 17 '08 at 4:27

 

Tom Leys

12.6k52756

 
9 

A recommendation to avoid using the heap is pretty strong. Modern systems have good heap managers, and modern dynamic languages use the heap extensively (without the programmer really worrying about it). I'd say use the heap, but with a manual allocator, don't forget to free! – Greg Hewgill Sep 17 '08 at 4:31

1 

If you can use the stack or the heap, use the stack. If you can't use the stack, really no choice. I use both a lot, and of course using std::vector or similar hits the heap. For a novice, you avoid the heap because the stack is simply so easy!! – Tom Leys Sep 17 '08 at 4:35

add a comment | 

up vote121down vote

To clarify, this answer has incorrect information (thomas fixed his answer after comments, cool :) ). 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/CPP and Python to help people understand.

"Static" (aka statically allocated) variables are not allocated on the stack. Do not assume so - many people do only because "static" sounds a lot like "stack". They actually exist in neither the stack nor the heap. The are part of what's called the data segment.

However it is generally better to consider "scope" and "lifetime" rather than "stack" and "heap".

Scope refers to what parts of the code can access a variable. Generally we think of local scope (can only be accessed by the current function) versus global scope (can be accessed anywhere) although scope can get much more complex.

Lifetime refers to when a variable is allocated and deallocated during program execution. Usually we think of static allocation (variable will persist through the entire duration of the program, making it useful for storing the same information across several function calls) versus automatic allocation (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 dynamic allocation (variables whose duration is defined at runtime, instead of compile time like static or automatic).

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).

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 :)

//statically allocated in the data segment when the program/DLL is first loaded 
//deallocated when the program/DLL exits
//scope - can be accessed from anywhere in the code
int someGlobalVariable;

//statically allocated in the data segment when the program is first loaded
//deallocated when the program/DLL exits
//scope - can be accessed from anywhere in this particular code file
static int someStaticVariable;

//"someArgument" is allocated on the stack each time MyFunction is called
//"someArgument" is deallocated when MyFunction returns
//scope - can be accessed only within MyFunction()
void MyFunction(int someArgument) {

    //statically allocated in the data segment when the program is first loaded
    //deallocated when the program/DLL exits
    //scope - can be accessed only within MyFunction()
    static int someLocalStaticVariable;

    //allocated on the stack each time MyFunction is called
    //deallocated when MyFunction returns
    //scope - can be accessed only within MyFunction()
    int someLocalVariable;

    //a *pointer* is allocated on the stack each time MyFunction is called
    //this pointer is deallocated when MyFunction returns
    //scope - the pointer can be accessed only within MyFunction()
    int* someDynamicVariable; 

    //this line causes space for an integer to be allocated in the heap
    //when this line is executed. note this is not at the beginning of 
    //the call to MyFunction(), like the automatic variables
    //scope - only code within MyFunction() can access this space
    //*through this particular variable*
    //however, if you pass the address somewhere else, that code
    //can access it too
    someDynamicVariable = new int; 


    //this line deallocates the space for the integer in the heap
    //if we did not write it, the memory would be "leaked"
    //note a fundamental difference b/w the stack and heap
    //the heap must be managed. the stack is managed for us
    delete someDynamicVariable;

    //in other cases, instead of deallocating this heap space you 
    //might store the address somewhere more permanent to use later
    //some languages even take care of deallocation for you... but
    //always it needs to be taken care of at runtime by some mechanism

    //when the function returns, someArgument, someLocalVariable
    //and the pointer someDynamicVariable are deallocated.
    //the space pointed to by someDynamicVariable was already
    //deallocated prior to returning
    return;
}

//note that someGlobalVariable, someStaticVariable and 
//someLocalStaticVariable continue to exist, and are not 
//deallocated until the program exits

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, "someLocalStaticVariable" in the code sample above. Such variables can make our common but informal naming habits very confusing. For instance when we say "local" we usually mean "locally scoped automatically allocated variable" and when we say global we usually mean "globally scoped statically allocated variable". Unfortunately when it comes to things like "file scoped statically allocated variables" many people just say... "huh???".

Some of the syntax choices in c/cpp exacerbate this problem - for instance many people think global variables are not "static" because of the syntax shown below.

int var1; //has global scope and static allocation
static int var2; //has file scope and static allocation

int main() {return 0;}

Note that putting the keyword "static" 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 "static" when describing scope, and instead say something like "file" or "file limited" scope. However many people use the phrase "static" or "static scope" to describe a variable that can only be accessed from one code file. In the context of lifetime, "static" always means the variable is allocated at program start and deallocated when program exits.

Some people think of these concepts as C/CPP 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).

from datetime import datetime

class Animal:
    _FavoriteFood = 'Undefined' #_FavoriteFood is statically allocated

    def PetAnimal(self):
        curTime = datetime.time(datetime.now()) #curTime is automatically allocatedion
        print("Thank you for petting me. But it's " + str(curTime) + ", you should feed me. My favorite food is " + self._FavoriteFood)

class Cat(Animal):
    _FavoriteFood = 'tuna' #note since we override, Cat class has its own statically allocated _FavoriteFood variable, different from Animal's

class Dog(Animal):
    _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!



if __name__ == "__main__":
    whiskers = Cat() #dynamically allocated
    fido = Dog() #dynamically allocated
    rinTinTin = Dog() #dynamically allocated

    whiskers.PetAnimal()
    fido.PetAnimal()
    rinTinTin.PetAnimal()

    Dog._FavoriteFood = 'milkbones'
    whiskers.PetAnimal()
    fido.PetAnimal()
    rinTinTin.PetAnimal()


# output is
# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is tuna
# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is steak
# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is steak
# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is tuna
# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is milkbones
# Thank you for petting me. But it's 13:05:02.256000, you should feed me. My favorite food is milkbones

share|improve this answer

edited Nov 18 '14 at 22:41

community wiki

 

18 revs, 4 users 99%
davec

 
   

I would refer to a static variable declared within a function as having only local accessibility, but would generally not use the term "scope" with it. Also, it may be worth noting that the one stack/heap aspect with which languages have essentially zero flexibility: a language which saves execution context on a stack cannot use that same stack to hold things which will need to outlive the contexts wherein they are created. Some languages like PostScript have multiple stacks, but have a "heap" that behaves more like a stack. – supercat Dec 9 '13 at 21:53

   

@supercat That all makes sense. I defined scope as "what parts of the code can access a variable" (and feel this is the most standard definition) so I think we agree :) – davec Dec 17 '13 at 20:28

   

I would regard the "scope" of a variable as being bounded by time as well as space. A variable at class-object scope is required to hold its value as long as the object exists. A variable within an execution-context scope is required to hold its value as long as execution remains in that context. A static variable declaration creates an identifier whose scope is bounded to the current block, which is attached to a variable whose scope is unbounded. – supercat Dec 17 '13 at 20:57

   

@supercat This is why I use the word lifetime, which is how I term what you call time scope. It reduces the need to overload the word "scope" with so many meanings. As far as I can tell, there doesn't seem to be total consensus on exact definitions though, even among canonical sources. My terminology is drawn partially from K&R and partially from the prevailing usage at the first CS department I studied/taught at. Always good to hear another informed view. – davec Dec 28 '13 at 22:50

1 

the most practical answer in here – Yerken Mar 22 at 2:41

 |  show 2 more comments

up vote120down vote

Others have answered the broad strokes pretty well, so I'll throw in a few details.

  1. 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.

  2. In C you can get the benefit of variable length allocation through the use of alloca, 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.

  3. On windows making a huge temporary buffer 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:

void myfunction()
{
   char big[10000000];
   // do something that only uses for first 1K of big 99% of the time.
}

share|improve this answer

edited Jan 3 '13 at 0:01

 

Alexander

1,83721428

answered Sep 17 '08 at 4:48

 

Don Neufeld

16.2k73846

 
  

add a comment | 

up vote89down vote

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 mmap()-based allocators). The Memory Management Glossary web page has a diagram of this memory layout.

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 setrlimit(RLIMIT_STACK, ...)). The heap grows when the memory allocator invokes the brk() or sbrk() system call, mapping more pages of physical memory into the process's virtual address space.

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 multiple stacks. In this sense, the stack is an element of the CPU architecture.

share|improve this answer

edited Aug 5 '15 at 20:36

 

EthanP

475618

answered Sep 17 '08 at 7:16

 

bk1e

17.6k43560

 
  

add a comment | 

up vote77down vote

I think many other people have given you mostly correct answers on this matter.

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.

share|improve this answer

answered Sep 17 '08 at 4:57

Heath

 
6 

Another nitpick- most of the answers (lightly) imply that the use of a "stack" is required by the C language. This is a common misconception, though it is the (by far) dominate paradigm for implementing C99 6.2.4 automatic storage duration objects (variables). In fact, the word "stack" does not even appear in the C99 language standard: open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf – johne Sep 1 '09 at 5:03

   

[@Heath] I have a small comment on your answer. Take a look at the accepted answer to this question. It says that the free store most probably is the same as the heap, though not necessarily is. – OmarOthman Feb 12 '12 at 6:34

add a comment | 

up vote75down vote

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.

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.

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)

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.

share|improve this answer

answered Sep 17 '08 at 4:29

 

Daniel Papasian

12.5k52129

 
1 

Also worth mentioning here that intel heavily optimizes stack accesses, especially things such as predicting where you return from a function. – Tom Leys Sep 17 '08 at 4:37

add a comment | 

up vote65down vote

You can do some interesting things with the stack. For instance, you have functions like alloca (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.

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.

share|improve this answer

answered Mar 19 '09 at 15:55

 

Peter

93863

 
  

add a comment | 

up vote57down vote

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.

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.

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.

share|improve this answer

edited Mar 19 '09 at 15:19

answered Mar 19 '09 at 15:13

T.E.D.

31k544111

 
   

[@T.E.D.] Why did you say "sometimes the parameters get pushed on the stack"? What I know is that they always are. Could you please elaborate more? – OmarOthman Feb 12 '12 at 6:36

1 

@OmarOthman - I say that because it is entirely up to the writer of your compiler/interpreter what happens when a subroutine is called. Classic Fortran behavior is to not use a stack at all. Some languages support exotic things like pass-by-name, which is effectively a textual substitution. – T.E.D. Apr 3 '12 at 15:57

add a comment | 

up vote47down vote

From WikiAnwser.

Stack

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.

This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.

The stack is important to consider in exception handling and thread executions.

Heap

The heap is simply the memory used by programs to store variables. Element of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.

I like the accepted answer better since it's even more low level.

share|improve this answer

answered Apr 2 '09 at 1:25

 

Chensformers

1,64122237

 
  

add a comment | 

up vote38down vote

My little contribution:

What is Stack?

Stack is a pile of objects, typically one that is neatly arranged.

enter image description here

Stacks in computing architectures are regions of memory where data is added or removed in a last-in-first-out manner.
In a multi-threaded application, each thread will have its own stack.

What is heap?

A heap is an untidy collection of things piled up haphazardly.

enter image description here

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.
Memory on the heap is allocated, deallocated, and resized regularly during program execution, and this can lead to a problem called fragmentation.
Fragmentation occurs when memory objects are allocated with small spaces in between that are too small to hold additional memory objects.
The net result is a percentage of the heap space that is not usable for further memory allocations.

Both together

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.

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.

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).

                                  Java Memory Model

enter image description here

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.
Every 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.

share|improve this answer

edited May 5 at 6:01

answered Jun 11 '14 at 19:42

Shreyos Adikari

5,250133857

 
   

@shreyisAdikari 'Java Memory Model' ?? what about other programming language?? – AminM Jul 28 at 18:12

   

@AminM This is just an example. – Shreyos Adikari Jul 28 at 20:54

add a comment | 

up vote33down vote

Stack

  • very fast access
  • don't have to explicitly de-allocate variables
  • space is managed efficiently by CPU, memory will not become fragmented
  • local variables only
  • limit on stack size (OS-dependent)
  • variables cannot be resized

Heap

  • variables can be accessed globally
  • no limit on memory size
  • (relatively) slower access
  • no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
  • you must manage memory (you're in charge of allocating and freeing variables)
  • variables can be resized using realloc()

share|improve this answer

answered Jan 30 '14 at 6:33

unknown

1,98712041

 
  

add a comment | 

up vote16down vote

In the 1980s, UNIX propagated like bunnies with big companies rolling their own. Exxon had one as did dozens of brand names lost to history. How memory was laid out was at the discretion of the many implementors.

A typical C program was laid out flat in memory with an opportunity to increase by changing the brk() value. Typically, the HEAP was just below this brk value and increasing brk increased the amount of available heap.

The single STACK was typically an area below HEAP which was a tract of memory containing nothing of value until the top of the next fixed block of memory. This next block was often CODE which could be overwritten by stack data in one of the famous hacks of its era.

One typical memory block was BSS (a block of zero values) which was accidentally not zeroed in one manufacturer's offering. Another was DATA containing initialized values, including strings and numbers. A third was CODE containing CRT (C runtime), main, functions, and libraries.

The advent of virtual memory in UNIX changes many of the constraints. There is no objective reason why these blocks need be contiguous, or fixed in size, or ordered a particular way now. Of course, before UNIX was Multics which didn't suffer from these constraints. Here is a schematic showing one of the memory layouts of that era.

A typical 1980s style UNIX C program memory layout

share|improve this answer

answered Mar 27 '15 at 19:55

 

jlettvin

410311

 
  

add a comment | 

up vote14down vote

  • Introduction

Physical memory is the range of the physical addresses of the memory cells in which an application or system stores its data, code, and so on during execution. Memory management denotes the managing of these physical addresses by swapping the data from physical memory to a storage device and then back to physical memory when needed. The OS implements the memory management services using virtual memory. As a C# application developer you do not need to write any memory management services. The CLR uses the underlying OS memory management services to provide the memory model for C# or any other high-level language targeting the CLR.

Figure 4-1 shows physical memory that has been abstracted and managed by the OS, using the virtual memory concept. Virtual memory is the abstract view of the physical memory, managed by the OS. Virtual memory is simply a series of virtual addresses, and these virtual addresses are translated by the CPU into the physical address when needed.

Figure 4-1. CLR memory abstraction enter image description here

The CLR provides the memory management abstract layer for the virtual execution environment, using the operating memory services. The abstracted concepts the CLR uses are AppDomain, thread, stack, heapmemorymapped file, and so on. The concept of the application domain (AppDomain) gives your application an isolated execution environment.

  • Memory Interaction between the CLR and OS

By looking at the stack trace while debugging the following C# application, using WinDbg, you will see how the CLR uses the underlying OS memory management services (e.g., the HeapFree method from KERNEL32.dll, the RtlpFreeHeap method from ntdll.dll) to implement its own memory model:

using System;
namespace CH_04
{
 class Program
 {
 static void Main(string[] args)
 {
 Book book = new Book();
 Console.ReadLine();
 }
 }
 public class Book
 {
 public void Print() { Console.WriteLine(ToString()); }
 }
}

The compiled assembly of the program is loaded into WinDbg to start debugging. You use the following commands to initialize the debugging session:

0:000> sxe ld clrjit

0:000> g

0:000> .loadby sos clr

0:000> .load C:\Windows\Microsoft.NET\Framework\v4.0.30319\sos.dll

Then, you set a breakpoint at the Main method of the Program class, using the !bpmd command:

0:000>!bpmd CH_04.exe CH_04.Program.Main

To continue the execution and break at the breakpoint, execute the g command:

0:000> g

When the execution breaks at the breakpoint, you use the !eestack command to view the stack trace details of all threads running for the current process. The following output shows the stack trace for all the threads running for the application CH_04.exe:

0:000> !eestack

Thread 0

Current frame: (MethodDesc 00233800 +0 CH_04.Program.Main(System.String[]))

ChildEBP RetAddr Caller, Callee

0022ed24 5faf21db clr!CallDescrWorker+0x33

/trace removed/

0022f218 77712d68 ntdll!RtlFreeHeap+0x142, calling ntdll!RtlpFreeHeap

0022f238 771df1ac KERNEL32!HeapFree+0x14, calling ntdll!RtlFreeHeap

0022f24c 5fb4c036 clr!EEHeapFree+0x36, calling KERNEL32!HeapFree

0022f260 5fb4c09d clr!EEHeapFreeInProcessHeap+0x24, calling clr!EEHeapFree

0022f274 5fb4c06d clr!operator delete[]+0x30, calling clr!EEHeapFreeInProcessHeap /trace removed/

0022f4d0 7771316f ntdll!RtlpFreeHeap+0xb7a, calling ntdll!_SEH_epilog4

0022f4d4 77712d68 ntdll!RtlFreeHeap+0x142, calling ntdll!RtlpFreeHeap

0022f4f4 771df1ac KERNEL32!HeapFree+0x14, calling ntdll!RtlFreeHeap

/trace removed/

This stack trace indicates that the CLR uses OS memory management services to implement its own memory model. Any memory operation in.NET goes via the CLR memory layer to the OS memory management layer.

Figure 4-2 illustrates a typical C# application memory model used by the CLR at runtime.

Figure 4-2. A typical C# application memory model enter image description here

The CLR memory model is tightly coupled with the OS memory management services. To understand the CLR memory model, it is important to understand the underlying OS memory model. It is also crucial to know how the physical memory address space is abstracted into the virtual memory address space, the ways the virtual address space is being used by the user application and system application, how virtual-to-physical address mapping works, how memory-mapped file works, and so on. This background knowledge will improve your grasp of CLR memory model concepts, including AppDomain, stack, and heap.

for more information refer this book: C# Deconstructed: Discover how C# works on the .NET Framework

http://www.amazon.com/Deconstructed-Discover-works-NET-Framework/dp/1430266708

this book + ClrViaC# + Windows Internals are excellent resources to known .net framework in depth and relation with OS.

share|improve this answer

edited Nov 10 '14 at 17:29

answered Nov 10 '14 at 17:22

 

programmer1

452615

 
  

add a comment | 

up vote11down vote

Since some answers went nitpicking, I'm going to contribute my mite.

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 fibers, green threads and some implementations of coroutines.

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 here.

In any case, the purpose of both fibers, green threads and coroutines is having multiple functions executing concurrently, but not in parallel (see this SO question for the distinction) within a single OS-level thread, transferring control back and forth from one another in an organized fashion.

When using fibers, green threads or coroutines, you usually 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, the number and lifetimes of stacks are dynamic and are not determined by the number of OS-level threads!

Note that I said "usually have a separate stack per function". There're both stackful and stackless implementations of couroutines. Most notable stackful C++ implementations are Boost.Coroutine and Microsoft PPL's async/await. (However, C++'s resumable functions (a.k.a. "async and await"), which were proposed to C++17, are likely to use stackless coroutines.)

Fibers proposal to the C++ standard library is forthcoming. Also, there're some third-party libraries. Green threads are extremely popular in languages like Python and Ruby.

share|improve this answer

edited Mar 2 '15 at 17:39

answered Mar 2 '15 at 1:29

shakurov

1,627717

 
  

add a comment | 

up vote10down vote

Couple cents: I think, will be good to draw memory graphical and more simple : This is my vision of process memory construction with simplification for more easy undersanding wht happening
Arrows - 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 Gb for example.
So simple way: process heap is general for process and all threads inside, using for memory allocation in common case with something like malloc().
Stack is quick memory for store in common case function return pointers and variables, processed as parameters in function call, local function variables.

share|improve this answer

answered Dec 17 '15 at 15:08

 

Maxim Akristiniy

573313

 
2 

Could you please translate this answer to English? – nbro Mar 15 at 11:26

add a comment | 

up vote4down vote

In Sort -

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .

In Detail-

The Stack-

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.

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.

More can be found here.

The Heap-

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. 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 valgrind that can help you detect memory leaks.

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.

Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.

More can be found here.

Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's 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.

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 . Element 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.

enter image description here

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 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.

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

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).

enter image description here

In run-time if the application needs more heap, it can allocate memory from free memory and if stack needs memory, it can allocate memory from free memory allocated memory for the application.

Even, more detail is given here and here.

Now come to your question's answers.

To what extent are they controlled by the OS or language runtime?

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.

More can be found here.

What is their scope?

Already given in top.

"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 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."

More can be found in here.

What determines the size of each of them?

The size of the stack is set by OS 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).

What makes one faster?

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.

Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.

Details can be found from here.

share|improve this answer

answered May 2 at 12:16

 

Abrar Jahin

2,44713052

 
  

add a comment | 

up vote0down vote

Heap is based on tree data structure with nodes and leaves. Nodes should have atleast one children and leaf is a single child element having no other child. The top most node is called root node. A depth first traversal(DFS) performed on heap starting at its root node has many applications with stack. Simply put, push() operation performed at the first visit of each node of the heap element increases the height of stack and a pop operation performed on stack decreases it when the same node element is revisited again.

For the following heap,started at root node element 100, the DFS results in following stack operations :

heap

push(100),  push(19), push (17), push(2),   pop(2),  push(7),
pop(7),    pop(17),    push(3),   pop(3),   pop(19) 

for the left sub-tree. Similarly, for the right sub-tree,

push(36), push(25), pop(25), push(1), pop(1), pop(36) and pop(100).

Hence the state of the stack remains same after completion of the traversal.

share|improve this answer

answered Jun 23 at 7:32

 

Vikranth Inti

516

 
   

Stack is mostly used within RAM whereas HEAP can be applied on RAM and secondary storage as well. – Vikranth Inti Jun 23 at 7:35

add a comment | 

protected by Charles Sep 13 '11 at 19:33

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged memory-management language-agnostic stack heap or ask your own question.

转载于:https://my.oschina.net/solarxie/blog/733052

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值