• 4가지 영역으로 구분
    • stack
      • 지역 변수, 함수 호출 정보
    • heap
      • malloc/new 로 만든 메모리
    • data
      • 초기값 있는, 없는 전역/정적 변수
      • 문자열 리터럴, 읽기 전용 변수
    • text
      • 기계어 코드(실행 코드)

Stack Segment

  • The stack stores local variables, function parameters, and return addresses for each function call.
  • Each function call creates a stack frame in this segment.
  • The stack is usually at higher memory addresses and grows opposite to the heap.
  • When the stack and heap meet, the program’s free memory is exhausted.
  •     #include <stdio.h>
      
      void func() {
          
          // Stored in the stack
          int local_var = 10;  
      }
      
      int main() {
          func();
          return 0;
      }

Heap Segment

  • The heap segment is used for dynamic memory allocation.
  • It starts at the end of the BSS segment and grows towards higher memory addresses.
  • Memory in the heap is managed using functions like malloc(), realloc(), and free().
  • The heap is shared by all shared libraries and dynamically loaded modules in a process.
  •   #include <stdio.h>
      #include <stdlib.h>
      
      int main() {
      	
      	// Create an integer pointer
      	int *ptr = (int*) malloc(sizeof(int) * 10); 
      	return 0;
      }

Data Segment

  • The data segment stores global and static variables of the program.
  • Variables in this segment retain their values throughout program execution.
  • The size of the data segment depends on the number and type of global/static variables.
  • It is divided into initialized and uninitialized (BSS) sections.
    • BSS - Block Started by Symbol

Text Segment

  • The text segment (or code segment) stores the executable code of the program like program’s functions and instructions.
  • The segment is usually read-only to prevent accidental modification during execution.
  • It is typically stored in the lower part of memory.
  • The size of the text segment depends on the number of instructions and the program’s complexity.