11.3 The stack and the heap

주홍영·2022년 3월 14일
0

Learncpp.com

목록 보기
117/199

https://www.learncpp.com/cpp-tutorial/the-stack-and-the-heap/

프로그램이 사용하는 메모리는 몇가지 area로 구분된다 이를 segment라고 한다

  • The code segment (also called a text segment), where the compiled program sits in memory. The code segment is typically read-only.

  • The bss segment (also called the uninitialized data segment), where zero-initialized global and static variables are stored.

  • The data segment (also called the initialized data segment), where initialized global and static variables are stored.

  • The heap, where dynamically allocated variables are allocated from.

  • The call stack, where function parameters, local variables, and other function-related information are stored.

이번 섹션에서는 우리는 heap과 stack에 대해서 중점적으로 다룬다

The heap segment

The heap has advantages and disadvantages:

  • Allocating memory on the heap is comparatively slow.
  • Allocated memory stays allocated until it is specifically deallocated (beware memory leaks) or the application ends (at which point the OS should clean it up).
  • Dynamically allocated memory must be accessed through a pointer. Dereferencing a pointer is slower than accessing a variable directly.
  • Because the heap is a big pool of memory, large arrays, structures, or classes can be allocated here.

The call stack

call stack, 호출 스택은 프로그램 시작부터 현재 실행 지점까지 모든 활성 함수(호출되었지만 아직 종료되지 않은 함수)를 추적하고 모든 함수 매개변수와 지역 변수의 할당을 처리합니다.

호출 스택은 스택 데이터 구조로 구현됩니다. 따라서 호출 스택이 작동하는 방식에 대해 이야기하기 전에 스택 데이터 구조가 무엇인지 이해해야 합니다.

The call stack segment

호출 스택 세그먼트는 호출 스택에 사용되는 메모리를 보유합니다. 애플리케이션이 시작되면 운영 체제에 의해 호출 스택에 main() 함수가 푸시됩니다. 그런 다음 프로그램이 실행되기 시작합니다.

함수 호출이 발생하면 함수가 호출 스택에 푸시됩니다. 현재 함수가 종료되면 해당 함수가 호출 스택에서 꺼집니다. 따라서 호출 스택에 푸시된 함수를 보면 현재 실행 지점에 도달하기 위해 호출된 모든 함수를 볼 수 있습니다.

위의 사서함 비유는 호출 스택이 작동하는 방식과 상당히 유사합니다. 스택 자체는 고정 크기의 메모리 주소 청크입니다. 메일박스는 메모리 주소이고 스택에 푸시하고 팝핑하는 "항목"을 스택 프레임이라고 합니다. 스택 프레임은 하나의 함수 호출과 관련된 모든 데이터를 추적합니다. 스택 프레임에 대해 조금 더 이야기하겠습니다. "마커"는 스택 포인터(때때로 "SP"로 축약됨)로 알려진 레지스터(CPU의 작은 메모리 조각)입니다. 스택 포인터는 현재 호출 스택의 맨 위 위치를 추적합니다.

한 가지 더 최적화할 수 있습니다. 호출 스택에서 항목을 팝할 때 스택 포인터를 아래로 이동하기만 하면 됩니다. 팝된 스택 프레임에서 사용하는 메모리를 정리하거나 0으로 만들 필요가 없습니다. 우편함 비우기). 이 메모리는 더 이상 "스택에" 있는 것으로 간주되지 않으므로(스택 포인터는 이 주소 또는 그 아래에 있음) 액세스되지 않습니다. 나중에 동일한 메모리에 새 스택 프레임을 푸시하면 정리하지 않은 이전 값을 덮어씁니다.

Stack overflow

stack은 한정된 메모리로 그 한정된 메모리를 넘어서 계속 push 된다면 stack overflow가 발생한다

예시로 너무 큰 데이터를 할당하려고 한더거나
무한재귀함수를 호출한다던지 하면 call stack이 overflow가 발생한다

profile
청룡동거주민

0개의 댓글