What and where are the stack and heap?

0 like 0 dislike
18 views

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 run-time?
  • What is their scope?
  • What determines the size of each of them?
  • What makes one faster?
by (550 points) | 18 views

1 Answer

0 like 0 dislike

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.

by (1.2k points)

Related questions

0 like 0 dislike
3 answers
asked Apr 11, 2019 by evgen9586
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
7 answers
110,608 questions
257,186 answers
0 comments
1,107 users