SlideShare uma empresa Scribd logo
1 de 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

Mais conteĂșdo relacionado

Mais procurados

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
 
test
testtest
testaaro11
 
MATLAB Scripts - Examples
MATLAB Scripts - ExamplesMATLAB Scripts - Examples
MATLAB Scripts - ExamplesShameer Ahmed Koya
 
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
 

Mais procurados (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
 

Semelhante a Introduction to c part -3

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptxBilalImran17
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in CVijayananda Ratnam Ch
 
(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-stringsNico Ludwig
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxNiharika606186
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxLECO9
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxSKUP1
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocationGrishma Rajput
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in clavanya marichamy
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdfKhaledIbrahim10923
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationUTTAM VERMA
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c languagekiran Patel
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 

Semelhante a 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
 

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

Mais 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
 

Último

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...gurkirankumar98700
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

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