1. What Are Stack Memory and Heap Memory?
When a program runs, it needs memory to store data during instruction execution, including local variables, function parameters, objects, dynamic data structures, and temporary computation results.
According to common runtime memory management models, memory regions can be abstracted into the stack and the heap.
1. Stack Memory
The stack is a data structure with last in, first out (LIFO) characteristics.
During program execution, function calls usually create a new stack frame to store the context information required for the current function's execution.
Typical contents include:
- Function parameters.
- Local variables.
- Return address.
- Saved register state.
- Temporary computation data.
- Data required by some calling conventions.
When the function call ends, the corresponding stack frame is usually released.
Typical characteristics of stack memory:
- Allocation and release usually have clear call boundaries.
- The lifetime is usually related to the function call process.
- Management overhead is relatively low.
- Access usually has good locality.
- Capacity is usually limited by the thread stack size.
2. Heap Memory
The heap is the region used for dynamic memory allocation.
During program execution, memory can be requested as needed and released at an appropriate time.
Typical contents include:
- Dynamically created objects.
- Dynamic arrays.
- Dynamic data structures such as linked lists and trees.
- Data whose lifetime spans multiple function calls.
- Complex data that needs dynamic management at runtime.
Typical characteristics of heap memory:
- Allocation timing is determined by the program's execution process.
- The lifetime does not have to be tied to function calls.
- It can support complex data structures.
- It requires additional memory management mechanisms.
- Problems such as memory fragmentation, allocation overhead, and lifetime management may occur.
3. Overall Relationship Between Stack and Heap
flowchart TD
A["Program Execution"] --> B["Memory Management"]
B --> C["Stack Memory"]
B --> D["Heap Memory"]
C --> E["Function Call Stack Frame"]
E --> F["Parameters, Local Variables, Return Information"]
D --> G["Dynamic Allocation Region"]
G --> H["Objects, Arrays, Dynamic Data Structures"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
It should be emphasized that the stack and the heap are concepts in the runtime memory management model. The actual memory layout may differ across languages, operating systems, virtual machines, and compilers. The above abstract structure should not be understood as a completely identical physical memory division for all programs.
2. How Stack Memory Works
1. Function Calls and Stack Frames
Function calls are the most important scenario for understanding stack memory.
Each function call usually needs to record the current execution state so that the caller's execution process can be restored after the function finishes.
This information is usually organized in a stack frame.
For example:
int add(int a, int b) {
int result = a + b;
return result;
}
int main() {
int x = 10;
int y = 20;
int sum = add(x, y);
return 0;
}
During execution, main and add each correspond to their own call context.
Conceptually, this can be understood as:
flowchart TD
A["Call main()"] --> B["Create main stack frame"]
B --> C["Execute code in main"]
C --> D["Call add()"]
D --> E["Create add stack frame"]
E --> F["Execute add()"]
F --> G["Return the result"]
G --> H["Release add stack frame"]
H --> I["Continue executing main()"]
I --> J["main() returns"]
J --> K["Release main stack frame"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E0F0FE,stroke:#93BCE8,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. The structure of a stack frame
A typical stack frame may contain the following:
| Content | Purpose |
|---|---|
| Parameters | Store the arguments received by the function |
| Local variables | Store variables defined inside the function |
| Return address | Record where to return after the function finishes executing |
| Saved registers | Preserve register state that must survive across calls |
| Temporary data | Store some intermediate computation results |
| Calling convention information | Support mechanisms such as argument passing and stack alignment |
The actual stack frame layout is determined by the processor architecture, the compiler, and the calling convention.
For example, on the x86-64 platform, some arguments may be passed through registers instead of all being placed on the stack.
Therefore, you cannot assume that all the parameters and local variables of every function are necessarily stored on the stack.
3. The last-in, first-out mechanism of the stack
Suppose function A calls function B, and function B in turn calls function C.
The call relationship:
flowchart TD
A["Function A"] --> B["Function B"]
B --> C["Function C"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The corresponding stack frame relationship:
Top of stack
┌──────────────────────────┐
│ Stack frame of function C│ ← called last
├──────────────────────────┤
│ Stack frame of function B│
├──────────────────────────┤
│ Stack frame of function A│ ← called first
└──────────────────────────┘
Bottom of stack
Function C returns first, then B, and finally A.
This is exactly the manifestation of last-in, first-out.
4. Recursion and stack overflow
Recursion is essentially a function repeatedly calling itself.
Each recursive call usually creates a new call context, so it continuously consumes call stack space.
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
When the input is large or the recursion lacks an effective termination condition, a large number of stack frames may be produced.
Eventually this may trigger a stack overflow (Stack Overflow).
flowchart TD
A["Call recursive function"] --> B["Create a new stack frame"]
B --> C{"Termination condition met?"}
C -->|"No"| D["Continue recursive calls"]
D --> B
C -->|"Yes"| E["Begin returning layer by layer"]
E --> F["Release stack frame"]
F --> G["Recursion ends"]
D --> H["Stack space keeps growing"]
H --> I["Exceed stack space limit"]
I --> J["Stack Overflow"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Not all recursion necessarily causes a stack overflow; whether it overflows depends on recursion depth, stack space size, compiler optimizations, and runtime implementation.
Some languages or runtime environments support tail-call optimization, which can reduce the stack space consumption of certain recursive calls, but you cannot assume that all languages automatically perform this optimization.
III. How Heap Memory Works
1. Dynamic Memory Allocation
The heap is mainly used to support dynamic allocation and management of memory during program execution.
Unlike stack memory, which usually follows the lifecycle of a function call, heap objects can continue to exist after a function returns.
Take C as an example:
#include <stdlib.h>
int main() {
int* p = malloc(sizeof(int));
if (p == NULL) {
return 1;
}
*p = 100;
free(p);
return 0;
}
Here:
malloc()allocates dynamic memory.- The returned pointer stores the address of the allocated memory.
*paccesses the data in that memory.free()releases the dynamically allocated memory.
The process of allocating and releasing heap memory can be abstracted as follows:
flowchart TD
A["Program needs dynamic memory"] --> B["Call the memory allocation interface"]
B --> C{"Allocation successful?"}
C -->|"No"| D["Handle allocation failure"]
C -->|"Yes"| E["Obtain memory address"]
E --> F["Use dynamic memory"]
F --> G["Memory no longer needed"]
G --> H["Release memory"]
H --> I["Memory available for later allocation"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. Lifecycle of Heap Memory
The lifecycle of a heap object does not necessarily match that of the function that creates it.
int* create_data() {
int* p = malloc(sizeof(int));
if (p == NULL) {
return NULL;
}
*p = 100;
return p;
}
After the function returns, the stack frame corresponding to the local pointer variable p ends, but the dynamically allocated memory is not automatically released as a result.
The caller can still access that memory through the returned pointer.
```c int main() { int* data = create_data(); if (data == NULL) { return 1; } printf("%d\n", *data); free(data); return 0; } ```This illustrates the difference in lifetime between stack variables and heap objects:
- A local pointer variable typically becomes invalid when the function call ends.
- Dynamically allocated memory must be released explicitly.
- A pointer variable going out of scope does not mean the memory it points to is freed automatically.
3. Heap Memory Management
Heap memory is not a simple contiguous-space allocator.
A runtime memory allocator usually has to track the state of memory blocks and handle operations such as allocation, freeing, coalescing, and reuse.
Common mechanisms include:
- Free lists.
- Memory block splitting and coalescing.
- Memory pools.
- Size classes.
- Buddy system.
- Thread-local caches.
- Page-level memory management.
Different languages and runtimes use different concrete strategies.
4. Memory Fragmentation
Frequently allocating and freeing memory blocks of different sizes can cause memory fragmentation.
It falls into two main categories.
External fragmentation:
Free memory is scattered across multiple non-contiguous regions.
Even when the total amount of free memory is sufficient, there may be no contiguous region large enough to satisfy a single allocation request.
Internal fragmentation:
The allocator hands out a block larger than the space actually needed, so part of the allocated space cannot be used effectively.
For example, if a program needs 30 bytes but the allocator allocates in units of 64 bytes, the leftover space can become internal fragmentation.
flowchart TD
A["Memory Fragmentation"] --> B["External Fragmentation"]
A --> C["Internal Fragmentation"]
B --> D["Free space scattered"]
B --> E["No contiguous region large enough"]
C --> F["Allocated block larger than actual need"]
C --> G["Unused space inside allocated regions"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
IV. Core Differences Between the Stack and the Heap
| Aspect | Stack memory | Heap memory |
|---|---|---|
| English term | Stack | Heap |
| Primary use | Function call context | Dynamic data allocation |
| Management | Usually managed automatically by the calling process | Managed by the allocator, garbage collector, or the program |
| Allocation | Usually done by adjusting the stack pointer | Usually done by a memory allocator |
| Deallocation | Usually reclaimed when the stack frame exits | Depends on the memory management mechanism |
| Lifetime | Usually tied to the call context | Can span function calls |
| Space characteristics | Usually smaller capacity, limited per thread | Usually larger capacity |
| Access characteristics | Usually has better locality | Access cost depends on object layout and access pattern |
| Typical risks | Stack overflow, dangling references | Memory leaks, fragmentation, dangling pointers |
Note that "the stack is faster and the heap is slower" is only a common rule of thumb; it does not hold in every scenario.
Actual performance is affected by many factors, including cache hit rate, allocator implementation, object layout, memory access patterns, and compiler optimizations.
V. Example of Stack and Heap Memory Layout
The following C program illustrates the relationship between variables, pointers, and dynamic memory.
#include <stdlib.h>
int main() {
int a = 10;
int* p = malloc(sizeof(int));
if (p == NULL) {
return 1;
}
*p = 20;
free(p);
return 0;
}
Conceptually:
ais a local variable.pis a local pointer variable.- The memory allocated by
malloc()is used to store the integer 20. pholds the address of the dynamic memory.
This can be abstracted as:
flowchart LR
subgraph S["Stack Memory (Stack)"]
A["Variable a<br/>10"]
P["Pointer variable p<br/>address"]
end
subgraph H["Heap Memory (Heap)"]
O["Dynamically allocated area<br/>20"]
end
P --> O
style S fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style H fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style P fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style O fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that this is a typical model intended to aid understanding. The C language standard does not mandate that local variables must be on the physical stack, nor does it guarantee that the implementation of malloc() must correspond to any particular fixed physical memory layout.
6. Stacks and Heaps in Different Programming Languages
The concepts of the stack and the heap are implemented differently in different languages.
1. C: Explicit Dynamic Memory Management
C provides interfaces for directly managing dynamic memory:
| Function | Purpose |
|---|---|
| malloc | Allocates memory of the specified size |
| calloc | Allocates and zero-initializes memory |
| realloc | Resizes previously allocated memory |
| free | Frees dynamic memory |
Example:
int* numbers = calloc(5, sizeof(int));
if (numbers == NULL) {
return 1;
}
numbers[0] = 100;
free(numbers);
numbers = NULL;
C does not automatically track usage of ordinary dynamic memory.
Programmers are responsible for managing memory lifetimes.
2. C++: Manual Management and RAII
While inheriting dynamic memory management capabilities, C++ provides higher-level resource management mechanisms.
Traditional dynamic allocation:
int* p = new int(100);
delete p;
Modern C++ recommends using smart pointers in appropriate scenarios:
#include <memory>
int main() {
auto p = std::make_unique<int>(100);
return 0;
}
std::unique_ptr manages resource lifetimes through RAII (Resource Acquisition Is Initialization).
When a smart pointer object goes out of scope, the dynamic object it manages is automatically released.
Shared ownership can use std::shared_ptr, but attention must be paid to reference counting and circular reference issues.
3. Java: The Virtual Machine Manages Heap Memory
Java runs on the JVM and has an automatic garbage collection mechanism.
public class Main {
public static void main(String[] args) {
User user = new User();
user.name = "Alice";
}
}
This can usually be understood as follows:
- user is a local variable in the method.
- The User object is managed by the runtime.
- When an object is no longer reachable and meets the collection conditions, it can be reclaimed by the garbage collector.
However, it cannot be simply assumed that all local variables in Java are on the stack and all objects are always on the heap.
The JVM can perform optimizations such as escape analysis and scalar replacement, changing the actual allocation and storage methods.
4. Python: Objects and Automatic Memory Management
Data in Python consists of objects.
def create_user():
user = {
"name": "Alice",
"age": 25
}
return user
data = create_user()
After the function returns, the local name user no longer exists, but the returned dictionary object can still be accessed through data.
In CPython, memory management mainly involves reference counting and cyclic garbage collection.
Other Python implementations may use different memory management strategies.
5. Go: Escape Analysis and Automatic Memory Management
Go uses automatic memory management and uses compiler escape analysis to determine the allocation location of some variables.
func createUser() *User {
user := User{
Name: "Alice",
}
return &user
}