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

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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 ...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

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 ) ; } }