SlideShare a Scribd company logo
1 of 9
C++ Memory
Management
Content
1. C++ Memory Segments
2. Program in RAM
3. Dynamic Memory
4. Call Stack
5. Call Stack Segment
6. Stack in Action
C++ Memory Segments
 A program is typically divide into different memory
areas called segments.
 Code Segment
 It also called text segment where the compiled program sits in
memory. The code segment is typically read-only.
 BSS Segment
 It is also called the uninitialized data segment, where zero-
initialized global and static variables are stored.
 Data Segment
 It is also called initialized data segment where initialized global
and static variables are stored
 Heap
 It holds dynamically allocated variables.
 Stack
 It stores function parameters, local variables, and other function-
related information.
Program in RAM
Sections:
1. Read only
a) .text: Program code.
b) .rodata: constants (const modifier)
and strings.
2. Global and Static
a) .data: Initialized global and static
variables (startup value ≠ 0)
b) .bss: Uninitialized global and static
variables (zero value on startup)
Dynamic Memory
Heap Segment (also known as the “free store”) keeps
track of memory used for dynamic memory allocation.
In C++, when you use the new operator to allocate memory,
this memory is allocated in the application’s heap segment.
 int *ptr = new int; // ptr is assigned 4 bytes in the heap
 int *array = new int[10]; // array is assigned 40 bytes in the heap
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.
Call Stack
Call stack usually referred to as “stack” .
The call stack keeps track of all the active functions from the start of the program to the current point of
execution, and handles allocation of all function parameters and local variables.
The call stack is implemented as a stack data structure.
A stack is a last-in, first-out (LIFO) structure. The last item pushed onto the stack will be the first item
popped off.
Stack has advantages and disadvantages:
1. Allocating memory on the stack is comparatively fast.
2. Memory allocated on the stack stays in scope as long as
it is on the stack. It is destroyed when it is popped off
the stack.
3. All memory allocated on the stack is known at compile
time. Consequently, this memory can be accessed
directly through a variable.
4. Because the stack is relatively small, it is generally not
a good idea to do anything that eats up lots of stack
space. This includes passing by value or creating local
variables of large arrays or other memory-intensive
structures, it leads to stack Overflow
Call Stack Segment
The Call Stack Segment holds the memory used for the call stack.
When a application function call is encountered, the function is pushed onto the call stack. When the current
function ends, that function is popped off the call stack. There is no need erase the memory just leave it to
be overwritten by the next item pushed to that piece of memory.
The stack itself is a fixed-size chunk of memory addresses,
and the “items” we’re pushing and popping on the stack are
called stack frames. A stack frame keeps track of all of the
data associated with one function call.
The “marker” is a register (a small piece of memory in the
CPU) known as the stack pointer (sometimes abbreviated
“SP”). The stack pointer keeps track of where the top of the
call stack currently is.
Call Stack in Action
How the call stack works?
Below is the sequence of steps that takes place when a function is called:
1. The program encounters a function call.
2. A stack frame is constructed and pushed on the stack. The stack frame consists of:
a) The address of the instruction beyond the function call (called the return address). This is how
the CPU remembers where to return to after the called function exits.
b) All function arguments.
c) Memory for any local variables.
d) Saved copies of any registers modified by the function that need to be restored when the function
returns
3. The CPU jumps to the function’s start point.
4. The instructions inside of the function begin executing.
When the function terminates, the following steps happen:
1. Registers are restored from the call stack
2. The stack frame is popped off the stack. This frees the memory for all local variables and arguments.
3. The return value is handled.
4. The CPU resumes execution at the return address
Questions?

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in javaVishnu Suresh
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cyclemyrajendra
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
Inline function
Inline functionInline function
Inline functionTech_MX
 

What's hot (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Applets
AppletsApplets
Applets
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java threads
Java threadsJava threads
Java threads
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Java History
Java HistoryJava History
Java History
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Python recursion
Python recursionPython recursion
Python recursion
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Inline function
Inline functionInline function
Inline function
 

Similar to C++ Memory Management

Similar to C++ Memory Management (20)

Buffer overflow attack
Buffer overflow attackBuffer overflow attack
Buffer overflow attack
 
C MEMORY MODEL​.pptx
C MEMORY MODEL​.pptxC MEMORY MODEL​.pptx
C MEMORY MODEL​.pptx
 
C MEMORY MODEL​.pptx
C MEMORY MODEL​.pptxC MEMORY MODEL​.pptx
C MEMORY MODEL​.pptx
 
Linux memorymanagement
Linux memorymanagementLinux memorymanagement
Linux memorymanagement
 
Malware Analysis - x86 Disassembly
Malware Analysis - x86 DisassemblyMalware Analysis - x86 Disassembly
Malware Analysis - x86 Disassembly
 
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacks
 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
 
(8) cpp stack automatic_memory_and_static_memory
(8) cpp stack automatic_memory_and_static_memory(8) cpp stack automatic_memory_and_static_memory
(8) cpp stack automatic_memory_and_static_memory
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
nasm_final
nasm_finalnasm_final
nasm_final
 
Run time storage
Run time storageRun time storage
Run time storage
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
Intermediate code optimization Unit-4.pdf
Intermediate code optimization Unit-4.pdfIntermediate code optimization Unit-4.pdf
Intermediate code optimization Unit-4.pdf
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Run time administration
Run time administrationRun time administration
Run time administration
 
Unit 5
Unit 5Unit 5
Unit 5
 
Cache memory
Cache memoryCache memory
Cache memory
 
Low Level Exploits
Low Level ExploitsLow Level Exploits
Low Level Exploits
 

More from Rahul Jamwal

Process & Mutlithreading
Process & MutlithreadingProcess & Mutlithreading
Process & MutlithreadingRahul Jamwal
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
Virtual Memory Management
Virtual Memory ManagementVirtual Memory Management
Virtual Memory ManagementRahul Jamwal
 
C++ shared libraries and loading
C++ shared libraries and loadingC++ shared libraries and loading
C++ shared libraries and loadingRahul Jamwal
 
C++ compilation process
C++ compilation processC++ compilation process
C++ compilation processRahul Jamwal
 

More from Rahul Jamwal (6)

Process & Mutlithreading
Process & MutlithreadingProcess & Mutlithreading
Process & Mutlithreading
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Data Structures
Data StructuresData Structures
Data Structures
 
Virtual Memory Management
Virtual Memory ManagementVirtual Memory Management
Virtual Memory Management
 
C++ shared libraries and loading
C++ shared libraries and loadingC++ shared libraries and loading
C++ shared libraries and loading
 
C++ compilation process
C++ compilation processC++ compilation process
C++ compilation process
 

Recently uploaded

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Recently uploaded (20)

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

C++ Memory Management

  • 2. Content 1. C++ Memory Segments 2. Program in RAM 3. Dynamic Memory 4. Call Stack 5. Call Stack Segment 6. Stack in Action
  • 3. C++ Memory Segments  A program is typically divide into different memory areas called segments.  Code Segment  It also called text segment where the compiled program sits in memory. The code segment is typically read-only.  BSS Segment  It is also called the uninitialized data segment, where zero- initialized global and static variables are stored.  Data Segment  It is also called initialized data segment where initialized global and static variables are stored  Heap  It holds dynamically allocated variables.  Stack  It stores function parameters, local variables, and other function- related information.
  • 4. Program in RAM Sections: 1. Read only a) .text: Program code. b) .rodata: constants (const modifier) and strings. 2. Global and Static a) .data: Initialized global and static variables (startup value ≠ 0) b) .bss: Uninitialized global and static variables (zero value on startup)
  • 5. Dynamic Memory Heap Segment (also known as the “free store”) keeps track of memory used for dynamic memory allocation. In C++, when you use the new operator to allocate memory, this memory is allocated in the application’s heap segment.  int *ptr = new int; // ptr is assigned 4 bytes in the heap  int *array = new int[10]; // array is assigned 40 bytes in the heap 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.
  • 6. Call Stack Call stack usually referred to as “stack” . The call stack keeps track of all the active functions from the start of the program to the current point of execution, and handles allocation of all function parameters and local variables. The call stack is implemented as a stack data structure. A stack is a last-in, first-out (LIFO) structure. The last item pushed onto the stack will be the first item popped off. Stack has advantages and disadvantages: 1. Allocating memory on the stack is comparatively fast. 2. Memory allocated on the stack stays in scope as long as it is on the stack. It is destroyed when it is popped off the stack. 3. All memory allocated on the stack is known at compile time. Consequently, this memory can be accessed directly through a variable. 4. Because the stack is relatively small, it is generally not a good idea to do anything that eats up lots of stack space. This includes passing by value or creating local variables of large arrays or other memory-intensive structures, it leads to stack Overflow
  • 7. Call Stack Segment The Call Stack Segment holds the memory used for the call stack. When a application function call is encountered, the function is pushed onto the call stack. When the current function ends, that function is popped off the call stack. There is no need erase the memory just leave it to be overwritten by the next item pushed to that piece of memory. The stack itself is a fixed-size chunk of memory addresses, and the “items” we’re pushing and popping on the stack are called stack frames. A stack frame keeps track of all of the data associated with one function call. The “marker” is a register (a small piece of memory in the CPU) known as the stack pointer (sometimes abbreviated “SP”). The stack pointer keeps track of where the top of the call stack currently is.
  • 8. Call Stack in Action How the call stack works? Below is the sequence of steps that takes place when a function is called: 1. The program encounters a function call. 2. A stack frame is constructed and pushed on the stack. The stack frame consists of: a) The address of the instruction beyond the function call (called the return address). This is how the CPU remembers where to return to after the called function exits. b) All function arguments. c) Memory for any local variables. d) Saved copies of any registers modified by the function that need to be restored when the function returns 3. The CPU jumps to the function’s start point. 4. The instructions inside of the function begin executing. When the function terminates, the following steps happen: 1. Registers are restored from the call stack 2. The stack frame is popped off the stack. This frees the memory for all local variables and arguments. 3. The return value is handled. 4. The CPU resumes execution at the return address