SlideShare a Scribd company logo
1 of 17
Dynamic Memory Allocation
2
Dynamic Memory Allocation
 Need to allocate memory dynamically
– If you want to change Array size as the need arise
 Dynamic Memory Allocation
– A process that allocate new storage while execute program
– Defined calloc() and malloc() function in stdlib.h
– calloc() means contiguous allocation
– malloc() means memory allocation
Use malloc() and calloc()
3
Dynamic Memory Allocation
 calloc()
– The size of each object is object_size byte. This function
allocates adjacent memory for the array that has n objects
– Each object is initialized with 0
– If success the call, it returns the address of allocated
memory.
– If not success the call, It returns NULL.
– Return type is void*
calloc ( n, object_size );
size of each objectnumber of objects
4
Dynamic Memory Allocation
 malloc()
– This function allocates the memory block of object_size byte
– It don’t initialize the memory space.
– If success the call, it returns the address of allocated
memory.
– If not success the call, It returns NULL.
– Return type is void*
malloc ( object_size );
size of each object
5
Dynamic Memory Allocation
 Example
#include <stdlib.h>
void main(void) {
char *p = (char*)malloc(26) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = ‘A’ + k ;
}
#include <stdlib.h>
void main(void) {
char *p = (char*)calloc(26, 1) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = ‘A’ + k ;
}
6
Dynamic Memory Allocation
 Example
#include <stdlib.h>
void main(void) {
int *p = (int*)malloc( 26*sizeof(int) ) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = k ;
}
#include <stdlib.h>
void main(void) {
int *p = (int*)calloc(26, sizeof(int) ) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = k ;
}
7
Dynamic Memory Allocation
 Example
#include <stdlib.h>
void main(void)
{
int (*a)[4] = (int**)malloc( 3*4*sizeof(int) ) ;
int i, j ;
for( i = 0 ; i < 3 ; i++ )
for( j = 0 ; j < 4 ; j++ )
a[i][j] = i+j ;
}
8
Dynamic Memory Allocation
 Example
#include <stdlib.h>
typedef int IntArray[4] ;
void main(void)
{
IntArray *a = (IntArray*)malloc( 3*sizeof(IntArray) ) ;
int i, j ;
for( i = 0 ; i < 3 ; i++ )
for( j = 0 ; j < 4 ; j++ )
a[i][j] = i+j ;
}
9
Dynamic Memory Allocation
 Example
#include <stdlib.h>
#include <string.h>
typedef struct student {
int std_id;
char name[20];
} Student;
void main(void) {
Student *p = (Student*)malloc( sizeof(Student) ) ;
p->std_id = 12345678 ;
strcpy( p->name, “Smith” ) ;
}
Dynamic Memory Allocation
 realloc()
– Resize the previously allocated memory space
– Copy the content to the newly allocated memory block
– Free the previous memory block
– Return the new memory block
10
ptr= realloc ( ptr, new_size );
11
Dynamic Memory Allocation
 Example
#include <stdlib.h>
void main(void) {
int *p = (int*)malloc( 10*sizeof(int) ) ;
int k ;
for( k = 0 ; k < 10 ; k++ ) p[k] = k ;
p = realloc( p, 20 ) ;
for(; k < 20 ; k++ ) p[k] = k ;
for( k = 0 ; k < 20 ; k++ )
printf( “%d “, p[k] ) ;
free( p ) ;
}
12
Dynamic Memory Allocation
 free()
– You can cancel the allocated memory using the free() when
you don’t need the memory allocated by calloc() or malloc()
any more.
[Ex]
p = malloc(26);
…
free(p);
Calling free() means cancellation
the memory block pointed by p
void free(void *ptr);
13
Dynamic Memory Allocation
 Dangling Pointer
– If you use the pointer that applied free()
[Ex]
char *p = malloc(40) ;
free(p);
p[0] = ‘A’ ;
printf( “%cn”, p[0] ) ;
1000
40 bytes
1000
p
1000p
free(p)
???
14
Dynamic Memory Allocation
 garbage
– If a large number of memory block (that allocated by calloc()
or malloc() and don't need any more) is leaved without
being free, then the system is out of memory gradually,
consequentially the program can't execute normally.
– Like that, unavailable memory block called garbage.
while( 1 ) {
p = malloc( 100 ) ;
}
15
Dynamic Memory Allocation
 garbage
void main()
{
int* p ;
p = malloc(100) ;
p = malloc(100) ;
…
}
1000
100 bytes
1000
p
2000
100 bytes
2000
p
100 bytes
1000
p =malloc(100)
16
Dynamic Memory Allocation
 Receive the random number of input,
then print them in reverse order
void main() {
int k, p[20], num ; //use array
while( 1 ) {
printf( “How many numbers?” ) ;
scanf( “%d”, &num ) ;
if( num < 0 ) break ;
for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ;
for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ;
}
}
17
Dynamic Memory Allocation
 Receive the random number of input,
then print them in reverse order
void main() {
int k, *p, num ; //use dynamic memory allocation
while( 1 ) {
printf( “How many numbers?” ) ;
scanf( “%d”, &num ) ;
if( num < 0 ) break ;
p = calloc( num, sizeof(int) ) ;
for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ;
for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ;
free( p ) ;
}
}

More Related Content

What's hot

Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c languagekiran Patel
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in clavanya marichamy
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in cPrabhu Govind
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesSubhajit Sahu
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocationFrijo Francis
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationMohammad Usman
 
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
 
decision tree regression
decision tree regressiondecision tree regression
decision tree regressionAkhilesh Joshi
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Namgee Lee
 

What's hot (20)

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 in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
L7 pointers
L7 pointersL7 pointers
L7 pointers
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
C dynamic ppt
C dynamic pptC dynamic ppt
C dynamic ppt
 
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
 
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...
 
decision tree regression
decision tree regressiondecision tree regression
decision tree regression
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Linked list
Linked listLinked list
Linked list
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 

Viewers also liked

02장 자료형과 연산자
02장 자료형과 연산자02장 자료형과 연산자
02장 자료형과 연산자웅식 전
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
03장 조건문반복문네임스페이스
03장 조건문반복문네임스페이스03장 조건문반복문네임스페이스
03장 조건문반복문네임스페이스웅식 전
 
9 object class
9 object class9 object class
9 object class웅식 전
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function웅식 전
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11 웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
11 1. multi-dimensional array eng
11 1. multi-dimensional array eng11 1. multi-dimensional array eng
11 1. multi-dimensional array eng웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 

Viewers also liked (19)

02장 자료형과 연산자
02장 자료형과 연산자02장 자료형과 연산자
02장 자료형과 연산자
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
03장 조건문반복문네임스페이스
03장 조건문반복문네임스페이스03장 조건문반복문네임스페이스
03장 조건문반복문네임스페이스
 
9 object class
9 object class9 object class
9 object class
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
13. structure
13. structure13. structure
13. structure
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
4. loop
4. loop4. loop
4. loop
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
10th
10th10th
10th
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
11 1. multi-dimensional array eng
11 1. multi-dimensional array eng11 1. multi-dimensional array eng
11 1. multi-dimensional array eng
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 

Similar to 13. dynamic allocation

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationGem WeBlog
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocationvaani pathak
 
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
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxVeerannaKotagi1
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocationbabuk110
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxhelpme43
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
(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
 

Similar to 13. dynamic allocation (20)

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dma
DmaDma
Dma
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
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
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
DMA.pptx
DMA.pptxDMA.pptx
DMA.pptx
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
(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
 

More from 웅식 전

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스웅식 전
 
Goorm ide open beta
Goorm ide open betaGoorm ide open beta
Goorm ide open beta웅식 전
 

More from 웅식 전 (18)

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
W14 chap13
W14 chap13W14 chap13
W14 chap13
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스
 
Goorm ide open beta
Goorm ide open betaGoorm ide open beta
Goorm ide open beta
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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
 
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
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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)
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

13. dynamic allocation

  • 2. 2 Dynamic Memory Allocation  Need to allocate memory dynamically – If you want to change Array size as the need arise  Dynamic Memory Allocation – A process that allocate new storage while execute program – Defined calloc() and malloc() function in stdlib.h – calloc() means contiguous allocation – malloc() means memory allocation Use malloc() and calloc()
  • 3. 3 Dynamic Memory Allocation  calloc() – The size of each object is object_size byte. This function allocates adjacent memory for the array that has n objects – Each object is initialized with 0 – If success the call, it returns the address of allocated memory. – If not success the call, It returns NULL. – Return type is void* calloc ( n, object_size ); size of each objectnumber of objects
  • 4. 4 Dynamic Memory Allocation  malloc() – This function allocates the memory block of object_size byte – It don’t initialize the memory space. – If success the call, it returns the address of allocated memory. – If not success the call, It returns NULL. – Return type is void* malloc ( object_size ); size of each object
  • 5. 5 Dynamic Memory Allocation  Example #include <stdlib.h> void main(void) { char *p = (char*)malloc(26) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = ‘A’ + k ; } #include <stdlib.h> void main(void) { char *p = (char*)calloc(26, 1) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = ‘A’ + k ; }
  • 6. 6 Dynamic Memory Allocation  Example #include <stdlib.h> void main(void) { int *p = (int*)malloc( 26*sizeof(int) ) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = k ; } #include <stdlib.h> void main(void) { int *p = (int*)calloc(26, sizeof(int) ) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = k ; }
  • 7. 7 Dynamic Memory Allocation  Example #include <stdlib.h> void main(void) { int (*a)[4] = (int**)malloc( 3*4*sizeof(int) ) ; int i, j ; for( i = 0 ; i < 3 ; i++ ) for( j = 0 ; j < 4 ; j++ ) a[i][j] = i+j ; }
  • 8. 8 Dynamic Memory Allocation  Example #include <stdlib.h> typedef int IntArray[4] ; void main(void) { IntArray *a = (IntArray*)malloc( 3*sizeof(IntArray) ) ; int i, j ; for( i = 0 ; i < 3 ; i++ ) for( j = 0 ; j < 4 ; j++ ) a[i][j] = i+j ; }
  • 9. 9 Dynamic Memory Allocation  Example #include <stdlib.h> #include <string.h> typedef struct student { int std_id; char name[20]; } Student; void main(void) { Student *p = (Student*)malloc( sizeof(Student) ) ; p->std_id = 12345678 ; strcpy( p->name, “Smith” ) ; }
  • 10. Dynamic Memory Allocation  realloc() – Resize the previously allocated memory space – Copy the content to the newly allocated memory block – Free the previous memory block – Return the new memory block 10 ptr= realloc ( ptr, new_size );
  • 11. 11 Dynamic Memory Allocation  Example #include <stdlib.h> void main(void) { int *p = (int*)malloc( 10*sizeof(int) ) ; int k ; for( k = 0 ; k < 10 ; k++ ) p[k] = k ; p = realloc( p, 20 ) ; for(; k < 20 ; k++ ) p[k] = k ; for( k = 0 ; k < 20 ; k++ ) printf( “%d “, p[k] ) ; free( p ) ; }
  • 12. 12 Dynamic Memory Allocation  free() – You can cancel the allocated memory using the free() when you don’t need the memory allocated by calloc() or malloc() any more. [Ex] p = malloc(26); … free(p); Calling free() means cancellation the memory block pointed by p void free(void *ptr);
  • 13. 13 Dynamic Memory Allocation  Dangling Pointer – If you use the pointer that applied free() [Ex] char *p = malloc(40) ; free(p); p[0] = ‘A’ ; printf( “%cn”, p[0] ) ; 1000 40 bytes 1000 p 1000p free(p) ???
  • 14. 14 Dynamic Memory Allocation  garbage – If a large number of memory block (that allocated by calloc() or malloc() and don't need any more) is leaved without being free, then the system is out of memory gradually, consequentially the program can't execute normally. – Like that, unavailable memory block called garbage. while( 1 ) { p = malloc( 100 ) ; }
  • 15. 15 Dynamic Memory Allocation  garbage void main() { int* p ; p = malloc(100) ; p = malloc(100) ; … } 1000 100 bytes 1000 p 2000 100 bytes 2000 p 100 bytes 1000 p =malloc(100)
  • 16. 16 Dynamic Memory Allocation  Receive the random number of input, then print them in reverse order void main() { int k, p[20], num ; //use array while( 1 ) { printf( “How many numbers?” ) ; scanf( “%d”, &num ) ; if( num < 0 ) break ; for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ; for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ; } }
  • 17. 17 Dynamic Memory Allocation  Receive the random number of input, then print them in reverse order void main() { int k, *p, num ; //use dynamic memory allocation while( 1 ) { printf( “How many numbers?” ) ; scanf( “%d”, &num ) ; if( num < 0 ) break ; p = calloc( num, sizeof(int) ) ; for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ; for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ; free( p ) ; } }