SlideShare a Scribd company logo
Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
Functions with heap and
stack
Jaseena A P
jsnp65@gmail.com
www.facebook.com/Jaseena
Muhammed A P
twitter.com/username
in.linkedin.com/in/profilena
me
9539443588
WHAT IS THE STACK?
The stack is a LIFO structure similar to packing items
in a box
•The last item placed into the box is the first item removed from the
box.
•However, the stack –like the box –has a fixed size and should NOT be
overflowed.
PUSH
POP
WHAT IS THE HEAP?
 A heap is a binary tree T that stores a key-element
pairs at its internal nodes
 It satisfies two properties:
• MinHeap: key(parent)  key(child)
• [OR MaxHeap: key(parent) ≥ key(child)]
• all levels are full, except the last one,
which is left-filled
4
6
207
811
5
9
1214
15
2516
WHAT IS THE HEAP?(contd..)
EXAMPLE FOR A MIN HEAP
MEMORY
What is memory?
Huge linear array of storage
How is memory divided?
Kernel space and user space
Who manages memory?
OS assigns memory to processes
Processes manage the memory they’ve been assigned
MEMORY ALLOCATION
 Memory allocation is a process by which computer programs
and services are assigned with physical or virtual memory space.
 Memory allocation is primarily a computer hardware operation
but is managed through operating system and software
applications.
 Programs and services are assigned with a specific memory as
per their requirements when they are executed. Once the
program has finished its operation or is idle, the memory is
released and allocated to another program or merged within the
primary memory.
ALLOCATION WITH STACK
When we have a declaration of the form “int a;”:
 a variable with identifier “a” and some memory allocated to it is
created in the stack. The attributes of “a” are:
• Name: a
• Data type: int
• Scope: visible only inside the function it is defined, disappears once
we exit the function
• Address: address of the memory location reserved for it.
Note: Memory is allocated in the stack for a even before it is
initialized.
• Size: typically 2 bytes
• Value: Will be set once the variable is initialized
Since the memory allocated for the variable is set in
the beginning itself, we cannot use the stack in
cases where the amount of memory required is not
known in advance. This motivates the need for
HEAP
ALLOCATION WITH STACK(CONTD..)
 The stack is a fixed block of memory, divided into two parts:
•Allocated memory used by the function that called the current
function, and the function called it etc.
•Free memory that can be allocated
 The borderline between the two areas is called the top of
stack and is represented by the stack pointer (SP), which is a
dedicated processor register
 Memory is allocated on the stack by moving the stack
pointer
ALLOCATION WITH STACK(CONTD..)
 very fast access
ALLOCATION WITH STACK(CONTD..)
 The main advantage of the stack is that functions in
different parts of the program can use the same
memory space to store their data
 Unlike a heap, a stack will never become fragmented
or suffer from memory leaks
 It is possible for a function to call itself—a recursive
function—and each invocation can store its own data
on the stack
ALLOCATION WITH STACK(CONTD..)
AN EXAMPLE
#include<stdio.h>
int factor(int );
void main()
{
int n,fact;
printf("Enter the numbern");
scanf("%d",&n);
fact=factor(n);
printf("Facorial is %d",fact);
}
int factor(int n)
{
int fct;
if(n==0)
fct=1;
else
fct=n*factor(n-1);
return fct;
}
Suppose n=4
Main()
n-2 bytes
Fact-2bytes
Factor(4)
fct-2bytes
Factor(3)
Factor(2)
Factor(1)
Factor(0)
fct-2bytes
fct-2bytes
fct-2bytes
fct-2bytes
Order of de-allocation
PROBLEMS WITH STACK
 The way the stack works makes it impossible to store
data that is supposed to live after the function returns.
The following function demonstrates a common
programming mistake. It returns a pointer to the variable
x, a variable that ceases to exist when the function
returns:
int*MyFunction()
{
intx;
/* Do something here. */
return &x; /* Incorrect */
}
PROBLEMS WITH STACK(contd..)
Another problem is the risk of running out of stack. This
will happen when one function calls another, which in
turn calls a third, etc., and the sum of the stack usage of
each function is larger than the size of the stack.
(STACK OVERFLOW)
•The risk is higher if large data objects are stored on
the stack, or when recursive functions are stored.
AN EXAMPLE
#include<stdio.h>
int factor(int );
void main()
{
int n,fact;
printf("Enter the numbern");
scanf("%d",&n);
fact=factor(n);
printf("Facorial is %d",fact);
}
int factor(int n)
{
int fct;
fct=n*factor(n-1);
return fct;
}
Main()-4 bytesSuppose n=4
Factor(4)-2 bytes
Factor(3)-2 bytes
Factor(2)-2 bytes
Factor(1)-2 bytes
Factor(0)-2 bytes
Factor(-1)-2 bytes
STACK OVERFLOW!!!
16bytes
PROBLEMS WITH STACK(contd..)
If the given stack size is too large, RAM will be wasted
If the given stack size is too small, two things can
happen, depending on where in memory ,the stack is
located:
•Variable storage will be overwritten, leading to undefined
behavior.
•The stack will fall outside of the memory area, leading to an
abnormal termination.
ALLOCATION WITH HEAP
•The heap is an area of memory reserved for dynamic
memory allocation
•When an application needs to use a certain amount of
memory temporarily it can allocate, or borrow, this
memory from the heap by calling the malloc( ) function in C
or by using the 'new' operator in C++
•When this memory is no longer needed it can be freed up
by calling free( ) or by using the delete operator. Once the
memory is freed it can reused by future allocations
ALLOCATION WITH HEAP(contd..)
•Variables can be accessed globally
•No limit on memory size
•(Relatively) slower access
•No guaranteed efficient use of space, memory may become fragmented
over time as blocks of memory are allocated, then freed
•Programmer must manage memory (he/she is in charge of allocating
and freeing variables)
•Variables can be resized using realloc()
AN EXAMPLE
#include <stdio.h>
int *sum(int *a,int *b)
{
int *c=malloc(sizeof(int));
/*find the sum here*/
return c;//return the sum
}
Void main()
{
int *x=malloc(sizeof(int));
int *y=malloc(sizeof(int));
int *z=malloc(sizeof(int));
/*read x and y*/
z=sum(x,y);
/*print the sum*/
free(x);
free(y);
free(z);
}
POTENTIAL PROBLEMS(contd..)
 Most common problems with dynamic memory
allocation occurs when blocks of memory of varying
size are frequently allocated and freed.
•When memory is freed, there will be a memory hole
•This can be a problem if the next allocation is larger than any of the
available hole.
•This can lead to difficulties in debugging since the total amount of
free space on the heap may be sufficient for a desired allocation but
allocation may fail since the free space is not contiguous.
POTENTIAL PROBLEMS(contd…)
7 bytes
12 bytes
STACK VS HEAP MEMORY ALLOCATION
STACK HEAP
Very fast access (Relatively) slower access
Don't have to explicitly de-allocate variables Explicit de-allocation is needed.
Space is managed efficiently by OS, memory
will not become fragmented
No guaranteed efficient use of space,
memory may become fragmented over time
as blocks of memory are allocated, then
freed
Local variables only Variables can be accessed globally
Limit on stack size (OS-dependent) No limit on memory size
Variables cannot be resized variables can be resized using realloc()
THANK YOU
If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

More Related Content

What's hot

Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
Muhammed Thanveer M
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
Frijo Francis
 
C dynamic ppt
C dynamic pptC dynamic ppt
C dynamic ppt
RJ Mehul Gadhiya
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
kiran Patel
 
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Mangalayatan university
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Burhanuddin Kapadia
 
Dynamic memory allocation in c language
Dynamic memory allocation in c languageDynamic memory allocation in c language
Dynamic memory allocation in c language
tanmaymodi4
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
MI RAKIB
 
TLPI - 7 Memory Allocation
TLPI - 7 Memory AllocationTLPI - 7 Memory Allocation
TLPI - 7 Memory Allocation
Shu-Yu Fu
 
memory
memorymemory
memory
teach4uin
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
Usha Mahalingam
 
Memory management
Memory managementMemory management
Memory management
sana younas
 
Heap Management
Heap ManagementHeap Management
Heap Management
Jenny Galino
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
John(Qiang) Zhang
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
Ilio Catallo
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structures
Wipro
 
Multi layered perceptron (mlp)
Multi layered perceptron (mlp)Multi layered perceptron (mlp)
Multi layered perceptron (mlp)
Handson System
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
Narayan Sau
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
gomathi chlm
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
Nguync91368
 

What's hot (20)

Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
C dynamic ppt
C dynamic pptC dynamic ppt
C dynamic ppt
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
 
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic memory allocation in c language
Dynamic memory allocation in c languageDynamic memory allocation in c language
Dynamic memory allocation in c language
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
TLPI - 7 Memory Allocation
TLPI - 7 Memory AllocationTLPI - 7 Memory Allocation
TLPI - 7 Memory Allocation
 
memory
memorymemory
memory
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Memory management
Memory managementMemory management
Memory management
 
Heap Management
Heap ManagementHeap Management
Heap Management
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structures
 
Multi layered perceptron (mlp)
Multi layered perceptron (mlp)Multi layered perceptron (mlp)
Multi layered perceptron (mlp)
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
 

Similar to Functions with heap and stack

Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Stack and heap
Stack and heapStack and heap
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
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
AkhilMishra50
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Rahul Jamwal
 
Presentation on Heap Sort
Presentation on Heap Sort Presentation on Heap Sort
Presentation on Heap Sort
Amit Kundu
 
Stack and heap
Stack and heapStack and heap
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
Mohamed Fawzy
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
Vinay Kumar
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
ngonidzashemutsipa
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
Senthil Kumar
 
Functions using stack and heap
Functions using stack and heapFunctions using stack and heap
Functions using stack and heap
baabtra.com - No. 1 supplier of quality freshers
 
C MEMORY MODEL​.pptx
C MEMORY MODEL​.pptxC MEMORY MODEL​.pptx
C MEMORY MODEL​.pptx
SKUP1
 
C MEMORY MODEL​.pptx
C MEMORY MODEL​.pptxC MEMORY MODEL​.pptx
C MEMORY MODEL​.pptx
LECO9
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
 
Functions with Heap and stack
 Functions with Heap and stack Functions with Heap and stack
Functions with Heap and stack
baabtra.com - No. 1 supplier of quality freshers
 
2.0 Stacks.pptx
2.0 Stacks.pptx2.0 Stacks.pptx
2.0 Stacks.pptx
MuhammadShajid1
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
sagaroceanic11
 
Functions
FunctionsFunctions

Similar to Functions with heap and stack (20)

Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
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
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Presentation on Heap Sort
Presentation on Heap Sort Presentation on Heap Sort
Presentation on Heap Sort
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Functions using stack and heap
Functions using stack and heapFunctions using stack and heap
Functions using stack and heap
 
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
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
Functions with Heap and stack
 Functions with Heap and stack Functions with Heap and stack
Functions with Heap and stack
 
2.0 Stacks.pptx
2.0 Stacks.pptx2.0 Stacks.pptx
2.0 Stacks.pptx
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Functions
FunctionsFunctions
Functions
 

More from baabtra.com - No. 1 supplier of quality freshers

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
Best coding practices
Best coding practicesBest coding practices
Core java - baabtra
Core java - baabtraCore java - baabtra
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php database connectivity
Php database connectivityPhp database connectivity
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Blue brain
Blue brainBlue brain
5g
5g5g
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Gd baabtra
Gd baabtraGd baabtra

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Recently uploaded

Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 

Recently uploaded (20)

Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 

Functions with heap and stack

  • 1.
  • 2. Disclaimer: This presentation is prepared by trainees of baabtra as a part of mentoring program. This is not official document of baabtra –Mentoring Partner Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt . Ltd
  • 3.
  • 4. Functions with heap and stack Jaseena A P jsnp65@gmail.com www.facebook.com/Jaseena Muhammed A P twitter.com/username in.linkedin.com/in/profilena me 9539443588
  • 5. WHAT IS THE STACK? The stack is a LIFO structure similar to packing items in a box •The last item placed into the box is the first item removed from the box. •However, the stack –like the box –has a fixed size and should NOT be overflowed. PUSH POP
  • 6. WHAT IS THE HEAP?  A heap is a binary tree T that stores a key-element pairs at its internal nodes  It satisfies two properties: • MinHeap: key(parent)  key(child) • [OR MaxHeap: key(parent) ≥ key(child)] • all levels are full, except the last one, which is left-filled
  • 7. 4 6 207 811 5 9 1214 15 2516 WHAT IS THE HEAP?(contd..) EXAMPLE FOR A MIN HEAP
  • 8. MEMORY What is memory? Huge linear array of storage How is memory divided? Kernel space and user space Who manages memory? OS assigns memory to processes Processes manage the memory they’ve been assigned
  • 9. MEMORY ALLOCATION  Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space.  Memory allocation is primarily a computer hardware operation but is managed through operating system and software applications.  Programs and services are assigned with a specific memory as per their requirements when they are executed. Once the program has finished its operation or is idle, the memory is released and allocated to another program or merged within the primary memory.
  • 10. ALLOCATION WITH STACK When we have a declaration of the form “int a;”:  a variable with identifier “a” and some memory allocated to it is created in the stack. The attributes of “a” are: • Name: a • Data type: int • Scope: visible only inside the function it is defined, disappears once we exit the function • Address: address of the memory location reserved for it. Note: Memory is allocated in the stack for a even before it is initialized. • Size: typically 2 bytes • Value: Will be set once the variable is initialized
  • 11. Since the memory allocated for the variable is set in the beginning itself, we cannot use the stack in cases where the amount of memory required is not known in advance. This motivates the need for HEAP ALLOCATION WITH STACK(CONTD..)
  • 12.  The stack is a fixed block of memory, divided into two parts: •Allocated memory used by the function that called the current function, and the function called it etc. •Free memory that can be allocated  The borderline between the two areas is called the top of stack and is represented by the stack pointer (SP), which is a dedicated processor register  Memory is allocated on the stack by moving the stack pointer ALLOCATION WITH STACK(CONTD..)
  • 13.  very fast access ALLOCATION WITH STACK(CONTD..)
  • 14.  The main advantage of the stack is that functions in different parts of the program can use the same memory space to store their data  Unlike a heap, a stack will never become fragmented or suffer from memory leaks  It is possible for a function to call itself—a recursive function—and each invocation can store its own data on the stack ALLOCATION WITH STACK(CONTD..)
  • 15. AN EXAMPLE #include<stdio.h> int factor(int ); void main() { int n,fact; printf("Enter the numbern"); scanf("%d",&n); fact=factor(n); printf("Facorial is %d",fact); } int factor(int n) { int fct; if(n==0) fct=1; else fct=n*factor(n-1); return fct; } Suppose n=4 Main() n-2 bytes Fact-2bytes Factor(4) fct-2bytes Factor(3) Factor(2) Factor(1) Factor(0) fct-2bytes fct-2bytes fct-2bytes fct-2bytes Order of de-allocation
  • 16. PROBLEMS WITH STACK  The way the stack works makes it impossible to store data that is supposed to live after the function returns. The following function demonstrates a common programming mistake. It returns a pointer to the variable x, a variable that ceases to exist when the function returns: int*MyFunction() { intx; /* Do something here. */ return &x; /* Incorrect */ }
  • 17. PROBLEMS WITH STACK(contd..) Another problem is the risk of running out of stack. This will happen when one function calls another, which in turn calls a third, etc., and the sum of the stack usage of each function is larger than the size of the stack. (STACK OVERFLOW) •The risk is higher if large data objects are stored on the stack, or when recursive functions are stored.
  • 18. AN EXAMPLE #include<stdio.h> int factor(int ); void main() { int n,fact; printf("Enter the numbern"); scanf("%d",&n); fact=factor(n); printf("Facorial is %d",fact); } int factor(int n) { int fct; fct=n*factor(n-1); return fct; } Main()-4 bytesSuppose n=4 Factor(4)-2 bytes Factor(3)-2 bytes Factor(2)-2 bytes Factor(1)-2 bytes Factor(0)-2 bytes Factor(-1)-2 bytes STACK OVERFLOW!!! 16bytes
  • 19. PROBLEMS WITH STACK(contd..) If the given stack size is too large, RAM will be wasted If the given stack size is too small, two things can happen, depending on where in memory ,the stack is located: •Variable storage will be overwritten, leading to undefined behavior. •The stack will fall outside of the memory area, leading to an abnormal termination.
  • 20. ALLOCATION WITH HEAP •The heap is an area of memory reserved for dynamic memory allocation •When an application needs to use a certain amount of memory temporarily it can allocate, or borrow, this memory from the heap by calling the malloc( ) function in C or by using the 'new' operator in C++ •When this memory is no longer needed it can be freed up by calling free( ) or by using the delete operator. Once the memory is freed it can reused by future allocations
  • 21. ALLOCATION WITH HEAP(contd..) •Variables can be accessed globally •No limit on memory size •(Relatively) slower access •No guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed •Programmer must manage memory (he/she is in charge of allocating and freeing variables) •Variables can be resized using realloc()
  • 22. AN EXAMPLE #include <stdio.h> int *sum(int *a,int *b) { int *c=malloc(sizeof(int)); /*find the sum here*/ return c;//return the sum } Void main() { int *x=malloc(sizeof(int)); int *y=malloc(sizeof(int)); int *z=malloc(sizeof(int)); /*read x and y*/ z=sum(x,y); /*print the sum*/ free(x); free(y); free(z); }
  • 23. POTENTIAL PROBLEMS(contd..)  Most common problems with dynamic memory allocation occurs when blocks of memory of varying size are frequently allocated and freed. •When memory is freed, there will be a memory hole •This can be a problem if the next allocation is larger than any of the available hole. •This can lead to difficulties in debugging since the total amount of free space on the heap may be sufficient for a desired allocation but allocation may fail since the free space is not contiguous.
  • 25. STACK VS HEAP MEMORY ALLOCATION STACK HEAP Very fast access (Relatively) slower access Don't have to explicitly de-allocate variables Explicit de-allocation is needed. Space is managed efficiently by OS, memory will not become fragmented No guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed Local variables only Variables can be accessed globally Limit on stack size (OS-dependent) No limit on memory size Variables cannot be resized variables can be resized using realloc()
  • 27. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 28. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: info@baabtra.com