CPP의 4가지 메모리

Ryan Ham·2024년 5월 30일
0

C++

목록 보기
22/26

스택(Stack)

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
}

힙(Heap)

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
}

코드 영역(Code segment)

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
}

데이터 영역(Data 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)
profile
🏦KAIST EE | 🏦SNU AI(빅데이터 핀테크 전문가 과정) | 📙CryptoHipsters 저자

0개의 댓글