The stack is a region of memory that stores local variables, function parameters, and return addresses. It operates in a last-in, first-out (LIFO) manner.
Automatic Storage Duration: Variables are automatically allocated and deallocated when the scope is entered and exited.
Function Call Management: Each function call creates a new stack frame to hold its local variables and return address.
Fast Allocation/Deallocation: Because the stack operates in a LIFO manner, pushing and popping stack frames is very fast.
Limited Size: The stack size is limited, and excessive use can lead to a stack overflow.
예시)
void function() {
int localVar = 10; // Stored on the stack
}
The heap is a region of memory used for dynamic memory allocation. Unlike the stack, memory in the heap must be manually managed using new and delete.
Dynamic Storage Duration: Memory is allocated and deallocated manually.
Flexible Size: The heap can grow as needed (up to the limit of the system's available memory).
Slower Allocation/Deallocation: Managing heap memory is slower compared to stack memory.
Potential for Fragmentation: Repeated allocations and deallocations can fragment the heap, leading to inefficient use of memory.
예시)
void function() {
int* dynamicVar = new int(10); // Stored on the heap
delete dynamicVar; // Must be manually deallocated
}
The code segment (also known as the text segment) stores the compiled machine code of the program.
Read-Only: Typically marked as read-only to prevent accidental modification of the program's instructions.
Executable Instructions: Contains the executable instructions of the program.
Fixed Size: The size of the code segment is determined at compile time and does not change at runtime.
예시)
void function() {
// Function instructions are stored in the code segment
}
The data segment is divided into two parts: the initialized data segment and the uninitialized data segment (BSS).
Initialized Data Segment: Stores global and static variables that are explicitly initialized.
Uninitialized Data Segment (BSS): Stores global and static variables that are not explicitly initialized.
Global Scope: Variables in the data segment are accessible throughout the program.
Fixed Size: The size of the data segment is determined at compile time and does not change at runtime.
예시)
int globalVar = 10; // Stored in the initialized data segment
static int staticVar; // Stored in the BSS (uninitialized data segment)