SlideShare a Scribd company logo
Gandhinagar Institute Of Technology
 Subject :-Computer Programming And Utilizaton ()
 Topic :- Dynamic Memory Allocation
 Branch :- Computer Engineering (CE)
 Division :- B
 Prepared By :- Grishma Rajput(160120107122)
 Submitted To :- Prof. Mihir Shah
Dynamic Memory Allocation
 In C, the exact size of array is unknown until compile time, i.e.,
the time when a compiler compiles your code into a computer
understandable language. So, sometimes the size of the array
can be insufficient or more than required.
 Dynamic memory allocation allows your program to obtain more
memory space while running, or to release it if it's not required.
 In simple terms, Dynamic memory allocation allows you to
manually handle memory space for your program.
 Although, C language inherently does not have any technique to
allocate memory dynamically, there are 4 library
functions under "stdlib.h" for dynamic memory allocation.
Memory Allocation Functions
Function Use of Function
malloc()
Allocates requested size of bytes and returns a pointer first
byte of allocated space
calloc()
Allocates space for an array elements, initializes to zero
and then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space
Memory Allocation Process
 Global variables, static variabl
es and program instructions get
their memory
in permanent storage area
whereas local variables are
stored in area called Stack.
 The memory space between
these two region is known
as Heap area. This region is
used for dynamic memory
allocation during execution of
the program. The size of heap
keep changing.
malloc()
 The name malloc stands for "memory allocation".
 The function malloc () reserves a block of memory of specified size and return
a pointer of type void which can be casted into pointer of any form.
 Syntax of malloc ()
 Here, ptr is pointer of cast-type. The malloc () function returns a pointer to an
area of memory with size of byte size. If the space is insufficient, allocation fails
and returns NULL pointer.
 This statement will allocate either 200 or 400 according to size of int 2 or 4
bytes respectively and the pointer points to the address of first byte of memory
ptr = (cast-type*) malloc(byte-size)
ptr = (int*) malloc(100 * sizeof(int));
malloc ( ) Example
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main ( )
{
int*p;
clrscr( );
p= (int*) malloc(1* sizeof ( int ));
*p=10;
printf(“n Value: %d”, *p);
free(p);
getch( );
}
OUT PUT:
Value : 10
calloc()
 The name calloc stands for "contiguous allocation".
 The only difference between malloc() and calloc() is that, malloc() allocates
single block of memory whereas calloc() allocates multiple blocks of
memory each of same size and sets all bytes to zero.
 Syntax of calloc()
 This statement will allocate contiguous space in memory for an array
of nelements. For example:
 This statement allocates contiguous space in memory for an array of 25
elements each of size of float, i.e, 4 bytes.
ptr = (float*) calloc(25, sizeof(float));
ptr = (cast-type*)calloc(n, element-size);
calloc ( ) Example
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main ( )
{
int*p;
clrscr( );
p= (int*) calloc(1, sizeof ( int ));
*p=10;
printf(“n Value: %d”, *p);
free(p);
getch( );
}
OUT PUT:
Value : 10
Difference between malloc() and calloc()
calloc() malloc()
calloc() initializes the allocated memory with
0 value.
malloc() initializes the allocated memory with
garbage values.
Number of arguments is 2 Number of argument is 1
Syntax :
(cast_type *)calloc(blocks , size_of_block);
Syntax :
(cast_type *)malloc(Size_in_bytes);
C free()
 Dynamically allocated memory created with either calloc() or
malloc() doesn't get freed on its own. You must explicitly use
free() to release the space.
 syntax of free()
 This statement frees the space allocated in the memory pointed
by ptr.
free(ptr);
C realloc()
 If the previously allocated memory is insufficient or more than
required, you can change the previously allocated memory
size using realloc().
 Syntax of realloc()
 This function allocates a new memory space of size new size
to the pointer variable ptr and returns a pointer to the first byte
of the new memory block. The new size may be larger or
smaller than the size.
 If the function is unsucessfull in locating additional space, it
returns NULL pointer and the original block is freed.
ptr = realloc(ptr, newsize);
relloc ( ) Incorrect Eample
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
int main()
{
int arr[2], i;
int *ptr = arr;
int *ptr_new;
arr[0] = 10;
arr[1] = 20;
// incorrect use of new_ptr: undefined behaviour
ptr_new = (int *) realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
getchar();
}
OUT PUT:
NULL
relloc( ) Correct Example
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *) malloc(sizeof(int)*2);
int i;
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *) realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr new + i));
getchar();
}
OUT PUT :
10 20 30
Thank you
Ad

More Related Content

What's hot (20)

Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
Shaina Arora
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Macro-processor
Macro-processorMacro-processor
Macro-processor
Temesgen Molla
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Arrays in c
Arrays in cArrays in c
Arrays in c
Jeeva Nanthini
 
Arrays searching-sorting
Arrays searching-sortingArrays searching-sorting
Arrays searching-sorting
Ajharul Abedeen
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
Mohd Arif
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
kiran Patel
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
5bit field
5bit field5bit field
5bit field
Frijo Francis
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Pointers - DataStructures
Pointers - DataStructuresPointers - DataStructures
Pointers - DataStructures
Omair Imtiaz Ansari
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
Shaina Arora
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Arrays searching-sorting
Arrays searching-sortingArrays searching-sorting
Arrays searching-sorting
Ajharul Abedeen
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
Mohd Arif
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
kiran Patel
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 

Similar to Dynamic Memory allocation (20)

dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
ngonidzashemutsipa
 
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptxLecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
roykaustav382
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
Dma
DmaDma
Dma
Joy Forerver
 
CLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.pptCLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.ppt
NikeshaPatel1
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
BilalImran17
 
Programming in C language specially allocation
Programming in C language specially allocationProgramming in C language specially allocation
Programming in C language specially allocation
DarkVibes4
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
LECO9
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
SKUP1
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
babuk110
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
vaani pathak
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
Shajahan T S Shah
 
Dma
DmaDma
Dma
Acad
 
Dynamic Memory Allocation in C programming
Dynamic Memory Allocation in C programmingDynamic Memory Allocation in C programming
Dynamic Memory Allocation in C programming
Rhishav Poudyal
 
Structures_and_Files[1] - Read-Only.pptx
Structures_and_Files[1]  -  Read-Only.pptxStructures_and_Files[1]  -  Read-Only.pptx
Structures_and_Files[1] - Read-Only.pptx
Ramesh Bssv
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
Frijo Francis
 
Memory Management for C and C++ _ language
Memory Management for C and C++ _ languageMemory Management for C and C++ _ language
Memory Management for C and C++ _ language
23ecuos117
 
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptxLecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
roykaustav382
 
CLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.pptCLanguage_ClassPPT_3110003_unit 9Material.ppt
CLanguage_ClassPPT_3110003_unit 9Material.ppt
NikeshaPatel1
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
BilalImran17
 
Programming in C language specially allocation
Programming in C language specially allocationProgramming in C language specially allocation
Programming in C language specially allocation
DarkVibes4
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
LECO9
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
SKUP1
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
babuk110
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
vaani pathak
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Dma
DmaDma
Dma
Acad
 
Dynamic Memory Allocation in C programming
Dynamic Memory Allocation in C programmingDynamic Memory Allocation in C programming
Dynamic Memory Allocation in C programming
Rhishav Poudyal
 
Structures_and_Files[1] - Read-Only.pptx
Structures_and_Files[1]  -  Read-Only.pptxStructures_and_Files[1]  -  Read-Only.pptx
Structures_and_Files[1] - Read-Only.pptx
Ramesh Bssv
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
Frijo Francis
 
Memory Management for C and C++ _ language
Memory Management for C and C++ _ languageMemory Management for C and C++ _ language
Memory Management for C and C++ _ language
23ecuos117
 
Ad

Recently uploaded (20)

Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Ad

Dynamic Memory allocation

  • 1. Gandhinagar Institute Of Technology  Subject :-Computer Programming And Utilizaton ()  Topic :- Dynamic Memory Allocation  Branch :- Computer Engineering (CE)  Division :- B  Prepared By :- Grishma Rajput(160120107122)  Submitted To :- Prof. Mihir Shah
  • 2. Dynamic Memory Allocation  In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles your code into a computer understandable language. So, sometimes the size of the array can be insufficient or more than required.  Dynamic memory allocation allows your program to obtain more memory space while running, or to release it if it's not required.  In simple terms, Dynamic memory allocation allows you to manually handle memory space for your program.  Although, C language inherently does not have any technique to allocate memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation.
  • 3. Memory Allocation Functions Function Use of Function malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory free() deallocate the previously allocated space realloc() Change the size of previously allocated space
  • 4. Memory Allocation Process  Global variables, static variabl es and program instructions get their memory in permanent storage area whereas local variables are stored in area called Stack.  The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.
  • 5. malloc()  The name malloc stands for "memory allocation".  The function malloc () reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.  Syntax of malloc ()  Here, ptr is pointer of cast-type. The malloc () function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.  This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory ptr = (cast-type*) malloc(byte-size) ptr = (int*) malloc(100 * sizeof(int));
  • 6. malloc ( ) Example #include<stdio.h> #include<conio.h> #include<stdlib.h> int main ( ) { int*p; clrscr( ); p= (int*) malloc(1* sizeof ( int )); *p=10; printf(“n Value: %d”, *p); free(p); getch( ); } OUT PUT: Value : 10
  • 7. calloc()  The name calloc stands for "contiguous allocation".  The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.  Syntax of calloc()  This statement will allocate contiguous space in memory for an array of nelements. For example:  This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. ptr = (float*) calloc(25, sizeof(float)); ptr = (cast-type*)calloc(n, element-size);
  • 8. calloc ( ) Example #include<stdio.h> #include<conio.h> #include<stdlib.h> int main ( ) { int*p; clrscr( ); p= (int*) calloc(1, sizeof ( int )); *p=10; printf(“n Value: %d”, *p); free(p); getch( ); } OUT PUT: Value : 10
  • 9. Difference between malloc() and calloc() calloc() malloc() calloc() initializes the allocated memory with 0 value. malloc() initializes the allocated memory with garbage values. Number of arguments is 2 Number of argument is 1 Syntax : (cast_type *)calloc(blocks , size_of_block); Syntax : (cast_type *)malloc(Size_in_bytes);
  • 10. C free()  Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You must explicitly use free() to release the space.  syntax of free()  This statement frees the space allocated in the memory pointed by ptr. free(ptr);
  • 11. C realloc()  If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().  Syntax of realloc()  This function allocates a new memory space of size new size to the pointer variable ptr and returns a pointer to the first byte of the new memory block. The new size may be larger or smaller than the size.  If the function is unsucessfull in locating additional space, it returns NULL pointer and the original block is freed. ptr = realloc(ptr, newsize);
  • 12. relloc ( ) Incorrect Eample #include <stdio.h> #include<conio.h> #include <stdlib.h> int main() { int arr[2], i; int *ptr = arr; int *ptr_new; arr[0] = 10; arr[1] = 20; // incorrect use of new_ptr: undefined behaviour ptr_new = (int *) realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr_new + i)); getchar(); } OUT PUT: NULL
  • 13. relloc( ) Correct Example #include <stdio.h> #include<conio.h> #include <stdlib.h> int main() { int *ptr = (int *) malloc(sizeof(int)*2); int i; int *ptr_new; *ptr = 10; *(ptr + 1) = 20; ptr_new = (int *) realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr new + i)); getchar(); } OUT PUT : 10 20 30