SlideShare une entreprise Scribd logo
1  sur  40
Recall
• What are functions used for?
• What happens when we declare a
varaible? Say int a;
• What is the difference between array and
structure?
• What is the output if i print *p, p, &p ?
Introduction to C
Memory Management
Week 3- day 1
When does memory
allocated in C?
• There are two ways in which memory can
be allocated in C:
–by declaring variables
–by explicitly requesting space from C
• Each case above space is allocated at
different sectors of RAM
Where does memory
allocated in C?
–by declaring variables -
Stack
–by explicitly requesting space from C
- Heap
Stack
Stack
• Stack is the place where all the
variables that are declared and
initialized before runtime are stored.
• Stack follows Last in First Out
order(LIFO)
• When the program finishes stack will
release all the spaces allocated for
variables.
Stack
12
32
322
34
main()
{
Int a=10,b=20,c;
c=sum(a,b);
}
int sum(int a,int b)
{
int c;
c=a+b;
return c;
}
RAM
Main()
a=10
b=20
c =30
sum()
a =10
b=20
C=30
What if there is no enough stack
space?
Stack
Main()
Aaa()
Bbb()
Ccc()
Ddd()
Eee()
Fff()Stack Over flow
Heap
Heap
• Heap is the area of memory used for
dynamic memory allocation
• Programmer allocates memory manually
at heap ; and hence variable on the heap
must be destroyed manually. There is no
automatic release as in stack23 32
43
452
89
How to allocate space in heap?
• C inbuilt functions
–Malloc() Allocates the
specified number of bytes
–Calloc() Allocates the
specified number of bytes
and initializes them to zero
–Realloc() Increases or decreases
the size of the specified
block of memory.
Reallocates it if needed
Malloc()
• malloc() stands for "memory allocation"
• The malloc() function dynamically
allocates memory when required.
• This function allocates „size‟ byte of
memory and returns a pointer to the first
byte or NULL if there is some kind of error
Syntax
malloc(size_in_bytes);
Malloc()
• Int *p;
• P=malloc(2);
HEAP
2 byte memory
Stack
1000
1000
All are same !
int *p;
p=malloc(2); //allocates 2 bytes of
memory
p=malloc(sizeof(Int)); //sizeof() returns
size of any data type
so here it will be mallloc(2)
p=(int *)malloc(2); //malloc always return
void * pointer . So you
may type cast it into any data type.
but it is unnecessary as the
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{ printf("Error! memory not allocated."); exit(0); }
Printf(“Enter the elements of Array”);
For(i=0;i<n;++i)
{
Scanf(“%d”,ptr+i);
Sum+=*(ptr+i);
}
Printf(“sum=%d”,sum);
free(ptr); // allocated memory is released
}
HEAPStack
n=10
1000ptr=1000
calloc()
• Calloc() stands for "contiguous allocation”
• Allocates multiple blocks of memory each of
same size and sets all bytes to zero
• Syntax
calloc(number_of_elements,size_in_byt
es);
Again we need a pointer to point to the
allocated space in heap
calloc()
• Int *p;
• P=calloc(3,10);
HEAP
10 bytes size
Stack
1000
1000
10 bytes size
10 bytes size
1001
1010
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{ printf("Error! memory not allocated."); exit(0); }
Printf(“Enter the elements of Array”);
For(i=0;i<n;++i)
{
Scanf(“%d”,ptr+i); // Scanf(“%d”,&ptr[i]);
Sum+=*(ptr+i);
}
Printf(“sum=%d”,sum);
free(ptr); // allocated memory is released
}
Malloc() Vs Calloc()
• Allocates "size" bytes of memory.
• The contents of
allocated memory are not changed.
i.e., the memory may contains
garbage values.
• returns void pointer (void *). If
the allocation succeeds, a pointer
to the block of memory is returned.
• Allocates
a region of memory large enough
to hold "n elements" of "size" bytes
each.
• The allocated region is initialized
to zero.
• returns void pointer (void *). If
the allocation succeeds, a pointer
to the block of memory is returned.
Structure of Ram
Structure of Ram
TEXT
Also known as the code segment,
holds the executable instructions
of a program.
• execute-only
• fixed size
Structure of Ram
A global variable that is initialized
and stored in the data segment.
This section has read/write
attributes but cannot be shared
among processes running the
same program.
Structure of Ram
This section holds uninitialized
data. This data consists of global
variables that the system
initializes with 0s upon program
execution. Another name for this
section is the zero-initialized data
section.
Structure of Ram
When a program uses malloc() to
obtain dynamic memory, this
memory is placed in the heap.
Structure of Ram
This contains all the local
variables that get allocated.
When a function is called, the
local variables for that function
are pushed onto the stack.
Questions?
“A good question deserve a good
grade…”
Self Check !!
Self Check
• When the program execution ends
variables in heap will be automatically
released
–True
–False
Self Check
• When the program execution ends
variables in heap will be automatically
released
–True
–False
Self Check
• Reference to the heap memory will be
stored in
•Heap
•Stack
•Gvar
•BSS
Self Check
• Reference to the heap memory will be
stored in
•Heap
•Stack
•Gvar
•BSS
Self Check
• Difference between malloc() and
calloc()
•Number of arguments
•No of blocks
•Initialization
•All of above
•None of above
Self Check
• Difference between malloc() and
calloc()
•Number of arguments
•No of blocks
•Initialization
•All of above
•None of above
Self Check
• Complete the below
Main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*) malloc (n*sizeof(int));
}
Self Check
• Complete the below
Main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*) malloc (n*sizeof(int));
}
Self Check
Free()
Malloc()
Heap
Callloc()
Stack
Variables
2 arguments
Automatically free the
memory
Automatically allocated
in stack
Reserves one block of
memory
Should be used when
Self Check
Free()
Malloc()
Heap
Callloc()
Stack
Variables
2 arguments
Automatically free the
memory
Automatically allocated
in stack
Reserves one block of
memory
Should be used when
main()
{
int i,a[10];
for(i=0;i<10;i++)
{
printf(“Enter the
number”);
scanf(“%d”,&a[i]);
}
main()
{
int i,*p,n;
printf(“Enter the number of
elements”);
scanf(“%d”,&n);
*p=calloc(n,sizeof(int));
for(i=0;i<10;i++)
{
printf(“Enter the
number”);
scanf(“%d”,&p [i]);
Self Check
main()
{
int i,a[10];
for(i=0;i<10;i++)
{
printf(“Enter the
number”);
scanf(“%d”,&a[i]);
}
main()
{
int i,*p,n;
printf(“Enter the number of
elements”);
scanf(“%d”,&n);
*p=calloc(n,sizeof(int));
for(i=0;i<10;i++)
{
printf(“Enter the
number”);
scanf(“%d”,&p [i]);
Self Check
End of Day 1

Contenu connexe

Tendances

computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8ecomputernotes
 
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
A look into the sanitizer family (ASAN & UBSAN) by Akul PillaiA look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
A look into the sanitizer family (ASAN & UBSAN) by Akul PillaiCysinfo Cyber Security Community
 
CNIT 127: Ch 2: Stack overflows on Linux
CNIT 127: Ch 2: Stack overflows on LinuxCNIT 127: Ch 2: Stack overflows on Linux
CNIT 127: Ch 2: Stack overflows on LinuxSam Bowne
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocationFrijo Francis
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementEelco Visser
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 ProcessShu-Yu Fu
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scriptsAmeen San
 
Конверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемыеКонверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемыеPlatonov Sergey
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerPlatonov Sergey
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsLovelitJose
 
Programming Environment in Matlab
Programming Environment in MatlabProgramming Environment in Matlab
Programming Environment in MatlabDataminingTools Inc
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional APIJustin Lin
 

Tendances (20)

computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8
 
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
A look into the sanitizer family (ASAN & UBSAN) by Akul PillaiA look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
 
CNIT 127: Ch 2: Stack overflows on Linux
CNIT 127: Ch 2: Stack overflows on LinuxCNIT 127: Ch 2: Stack overflows on Linux
CNIT 127: Ch 2: Stack overflows on Linux
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
Manipulators
ManipulatorsManipulators
Manipulators
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
 
Конверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемыеКонверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемые
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
test
testtest
test
 
MATLAB Scripts - Examples
MATLAB Scripts - ExamplesMATLAB Scripts - Examples
MATLAB Scripts - Examples
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-Expressions
 
Programming Environment in Matlab
Programming Environment in MatlabProgramming Environment in Matlab
Programming Environment in Matlab
 
Go1
Go1Go1
Go1
 
1 c prog1
1 c prog11 c prog1
1 c prog1
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional API
 

Similaire à Introduction to c part -3

Similaire à Introduction to c part -3 (20)

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
Dma
DmaDma
Dma
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Functions using stack and heap
Functions using stack and heapFunctions using stack and heap
Functions using stack and heap
 
Buffer overflow attack
Buffer overflow attackBuffer overflow attack
Buffer overflow attack
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
Scope Stack Allocation
Scope Stack AllocationScope Stack Allocation
Scope Stack Allocation
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
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
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 

Plus de baabtra.com - No. 1 supplier of quality freshers

Plus de 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
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Introduction to c part -3

  • 1. Recall • What are functions used for? • What happens when we declare a varaible? Say int a; • What is the difference between array and structure? • What is the output if i print *p, p, &p ?
  • 2. Introduction to C Memory Management Week 3- day 1
  • 3. When does memory allocated in C? • There are two ways in which memory can be allocated in C: –by declaring variables –by explicitly requesting space from C • Each case above space is allocated at different sectors of RAM
  • 4. Where does memory allocated in C? –by declaring variables - Stack –by explicitly requesting space from C - Heap
  • 6. Stack • Stack is the place where all the variables that are declared and initialized before runtime are stored. • Stack follows Last in First Out order(LIFO) • When the program finishes stack will release all the spaces allocated for variables. Stack 12 32 322 34
  • 7. main() { Int a=10,b=20,c; c=sum(a,b); } int sum(int a,int b) { int c; c=a+b; return c; } RAM Main() a=10 b=20 c =30 sum() a =10 b=20 C=30
  • 8. What if there is no enough stack space? Stack Main() Aaa() Bbb() Ccc() Ddd() Eee() Fff()Stack Over flow
  • 10. Heap • Heap is the area of memory used for dynamic memory allocation • Programmer allocates memory manually at heap ; and hence variable on the heap must be destroyed manually. There is no automatic release as in stack23 32 43 452 89
  • 11. How to allocate space in heap? • C inbuilt functions –Malloc() Allocates the specified number of bytes –Calloc() Allocates the specified number of bytes and initializes them to zero –Realloc() Increases or decreases the size of the specified block of memory. Reallocates it if needed
  • 12. Malloc() • malloc() stands for "memory allocation" • The malloc() function dynamically allocates memory when required. • This function allocates „size‟ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error Syntax malloc(size_in_bytes);
  • 13. Malloc() • Int *p; • P=malloc(2); HEAP 2 byte memory Stack 1000 1000
  • 14. All are same ! int *p; p=malloc(2); //allocates 2 bytes of memory p=malloc(sizeof(Int)); //sizeof() returns size of any data type so here it will be mallloc(2) p=(int *)malloc(2); //malloc always return void * pointer . So you may type cast it into any data type. but it is unnecessary as the
  • 15. #include <stdio.h> #include <stdlib.h> void main() { int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==NULL) { printf("Error! memory not allocated."); exit(0); } Printf(“Enter the elements of Array”); For(i=0;i<n;++i) { Scanf(“%d”,ptr+i); Sum+=*(ptr+i); } Printf(“sum=%d”,sum); free(ptr); // allocated memory is released } HEAPStack n=10 1000ptr=1000
  • 16. calloc() • Calloc() stands for "contiguous allocation” • Allocates multiple blocks of memory each of same size and sets all bytes to zero • Syntax calloc(number_of_elements,size_in_byt es); Again we need a pointer to point to the allocated space in heap
  • 17. calloc() • Int *p; • P=calloc(3,10); HEAP 10 bytes size Stack 1000 1000 10 bytes size 10 bytes size 1001 1010
  • 18. #include <stdio.h> #include <stdlib.h> void main() { int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc if(ptr==NULL) { printf("Error! memory not allocated."); exit(0); } Printf(“Enter the elements of Array”); For(i=0;i<n;++i) { Scanf(“%d”,ptr+i); // Scanf(“%d”,&ptr[i]); Sum+=*(ptr+i); } Printf(“sum=%d”,sum); free(ptr); // allocated memory is released }
  • 19. Malloc() Vs Calloc() • Allocates "size" bytes of memory. • The contents of allocated memory are not changed. i.e., the memory may contains garbage values. • returns void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned. • Allocates a region of memory large enough to hold "n elements" of "size" bytes each. • The allocated region is initialized to zero. • returns void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
  • 21. Structure of Ram TEXT Also known as the code segment, holds the executable instructions of a program. • execute-only • fixed size
  • 22. Structure of Ram A global variable that is initialized and stored in the data segment. This section has read/write attributes but cannot be shared among processes running the same program.
  • 23. Structure of Ram This section holds uninitialized data. This data consists of global variables that the system initializes with 0s upon program execution. Another name for this section is the zero-initialized data section.
  • 24. Structure of Ram When a program uses malloc() to obtain dynamic memory, this memory is placed in the heap.
  • 25. Structure of Ram This contains all the local variables that get allocated. When a function is called, the local variables for that function are pushed onto the stack.
  • 26. Questions? “A good question deserve a good grade…”
  • 28. Self Check • When the program execution ends variables in heap will be automatically released –True –False
  • 29. Self Check • When the program execution ends variables in heap will be automatically released –True –False
  • 30. Self Check • Reference to the heap memory will be stored in •Heap •Stack •Gvar •BSS
  • 31. Self Check • Reference to the heap memory will be stored in •Heap •Stack •Gvar •BSS
  • 32. Self Check • Difference between malloc() and calloc() •Number of arguments •No of blocks •Initialization •All of above •None of above
  • 33. Self Check • Difference between malloc() and calloc() •Number of arguments •No of blocks •Initialization •All of above •None of above
  • 34. Self Check • Complete the below Main() { int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*) malloc (n*sizeof(int)); }
  • 35. Self Check • Complete the below Main() { int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*) malloc (n*sizeof(int)); }
  • 36. Self Check Free() Malloc() Heap Callloc() Stack Variables 2 arguments Automatically free the memory Automatically allocated in stack Reserves one block of memory Should be used when
  • 37. Self Check Free() Malloc() Heap Callloc() Stack Variables 2 arguments Automatically free the memory Automatically allocated in stack Reserves one block of memory Should be used when
  • 38. main() { int i,a[10]; for(i=0;i<10;i++) { printf(“Enter the number”); scanf(“%d”,&a[i]); } main() { int i,*p,n; printf(“Enter the number of elements”); scanf(“%d”,&n); *p=calloc(n,sizeof(int)); for(i=0;i<10;i++) { printf(“Enter the number”); scanf(“%d”,&p [i]); Self Check
  • 39. main() { int i,a[10]; for(i=0;i<10;i++) { printf(“Enter the number”); scanf(“%d”,&a[i]); } main() { int i,*p,n; printf(“Enter the number of elements”); scanf(“%d”,&n); *p=calloc(n,sizeof(int)); for(i=0;i<10;i++) { printf(“Enter the number”); scanf(“%d”,&p [i]); Self Check