Language Study/C

[C/C++] 10 - 03 Lifetime 분류

지미닝 2022. 12. 14. 03:30

Index

  1. 변수(또는 메모리 블록) Lifetmie 분류
  2. Memory Layout of a C Process
    1. 함수 호출과 Stack
    2. Automatic Variable & Stack

1. 변수(또는 메모리 블록) Lifetime 분류

① Static

  • Its lifetime is the entire duration of the program's execution
  • Global and Static Local Variables
  • A static variable is stored in the data segment of the "object file" of a program

② Automatic

  • An automatic variable has a lifetime that begins when program execution enters the function or statement block or compound and ends when execution leaves the block.
  • Non-static Local Variables
  • Automatic variables are stored in a "function call stack"

③ Dynamic

  • The lifetime of a dynamic object begins when memory is allocated for the object (e.g., by a call to malloc()) and ends when memory is deallocated (e.g., by a call to free()).
  • Dynamic objects are stored in "the heap"

 

2. Memory Layout of a C Process

Process: 수행 중인 프로그램

Process Image: Process가 점유하고 있는 메모리 구획

정적 공간

  • Text Segment: 수행할 명령어를 포함하며 프로그램 구동 중 내용이 변하지 않음
  • Data Segment: Static 변수와 문자열 상수를 위한 메모리 공간
    • 프로그램 수행 전체 시간 동안 변수 공간 유지

동적 공간

  • 메모리 공간의 제약을 고려
    • 변수와 메모리 블록이 필요한 시점에만 메모리를 할당하여 그 사용이 끝난 시점에 해제
    • 작은 메모리로도 효과적인 프로그램 작성 가능
  • Stack: Automatic 변수를 위한 공간
    • 함수를 시작하며 Automatic 변수를 동적으로 생성하여 메모리를
    • 함수가 종료되면 메모리를 해제하고 변수를 삭제
    • 함수가 호출되면서 기존 공간 위에 쌓여져 감
      • Stack: 쌓다. 실제 메모리 주소는 줄어들기 때문에 쌓인다는 표현이 어색할수도 있음
  • Heap: Dynamic 변수를 위한 공간
    • 동적 할당이라는 점에서 Stack과 유사
    • 자동으로 할당되는 것이 아니라 코드에서 malloc()을 통해 명시적으로 할당 받고 free()를 통해 명시적으로 Deallocate/free하여야 한다는 점에서 차이가 남
  • Stack 또는 Heap 공간의 부족
    • Heap의 경우 malloc()에 실패
    • Stack - Stack Overflow가 발생하영 Run Time Error

 

2 - 1 함수 호출과 Stack

함수 호출에 따른 Stack 공간 변화

 

2 - 2 Automatic Variable & Stack