SlideShare a Scribd company logo
1 of 24
DYNAMIC MEMORY
ALLOCATION IN C
BY GROUP 4
SOFTWARE ENGINEERING
CONTENTS
1. Introduction to topic
2. Theory of dynamic memory allocation
3. Stdlib.h functions
4. Malloc
5. Calloc
6. Realloc
7. Free
8. Presentation of the code on an IDE
9. Difference between dynamic and static memory allocation
10. Summary
WHAT IS ALLOCATION?
AN ALLOCATION IS SOMETHING THAT YOU
SET ASIDE FOR USE. FOR INSTANCE IF YOU
WANT TO SET ASIDE A CERTAIN AMOUNT OF
HARD DRIVE SPACE FOR AN APPLICATION.
MEMORY ALLOCATION IS THE PROCESS OF
SETTING ASIDE SECTION OF MEMORY IN A
PROGRAM TO BE USED TO STORE VARIABLES,
AND INSTANCES OF STRUCTURE AND
CLASSES.
INTRODUCTION
WHAT IS DYNAMIC MEMORY ALLOCATION?
Dynamic memory allocation in C is the process of allocating memory at
runtime. Dynamic memory allocation is useful for creating data structures
that need to be variable in size, such as arrays, linked lists, and trees.
• Heap Allocation: The memory is allocated during the
execution of instructions written by programmers.
• It is called a heap because it is a pile of memory space
available to programmers to allocate and de-allocate.
• If a programmer does not handle this memory well, a
memory leak can happen in the program.
• Stack: allocates or de-allocates the memory
automatically as soon as the corresponding method
completes its execution.
The term 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.
Malloc allocates a contiguous block of memory.
If enough contiguous memory is not available,
then malloc returns NULL
MALLOC
MEMORY ALLOCATION CHECK
 to make sure memory allocation was successful we use:
void* p;
if ((p=malloc(n)) == NULL)
return 1;
else
{ /* memory is allocated */}
SYNTAX
 size_t : stores only positive integer value, you can think of this
particular datatype as unsigned integer datatype.
 size cannot be negative , it can be either positive or zero value.
 Malloc return a void pointer that gives us the address of the first
byte in the block of memory that it allocates.
void * malloc(size_t size);
EXAMPLE
void *malloc(2*sizeof(int)); //(no of elements * size of one unit)
• this will store 2 * 4 = 8 byte on the memory say from address 201 to 208 ie.
• It allocates a block of memory for array of 2 integer , each of 4 byte
Value 1 Value 2
201 208
• so the malloc will return void ptr to the address of the first byte i.e 201.
• if we want to store values at these addresses.
• As malloc return void ptr, and void ptr cannot be de-referenced, so we cannot directly assign the values as *p
= 2;void ptr can be typecasted into a pointer type of particular datatype and then it is used.
• Inorder to use this block of memory we first need to typecast this void pointer of some datatype like
thisSyntax :
pointer = (type) malloc (size in bytes);
EXAMPLE
ptr=(int*)malloc(2*sizeof(int));//2*4=8bytes
By asking memory block of 2 integers, we are basically creating an array of integers with 2 elements.
Assigning values to the address :
ptr = 2; // this will assign value at the address say 201
(ptr + 1) = 3; // this will assign value at the address 205
EXAMPLE OF MALLOC
OUTPUT
CALLOC
• It is used to allocate multiple block of requested memory with
the same givenmemory size of memory for each block
• it initializes all bytes to zero
• It returns NULL if the memory is not sufficient
SYNTAX
void*calloc(size_t n, size_t size)
ptr =(cast - type*)calloc(number,byte size);
• Cast type - represents the data types that we are using for type casting
• Number of block - number of blocks it will allocate / number of elements in
the data type
• Size of block- size of one single block / size of data type
EXAMPLE
ptr =(int*)calloc(n,size);
ptr=(int*)calloc(n,sizeof(int))
ptr =(float*)calloc(25,sizeof(float)); // space is created for 25 elements eachof size of a float (4 bits)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int*ptr;//this pointer will hold the base address of created memory blocks
int n=5;//Let say we have to create 5 blocks
int size=sizeof(int);//lets say we want to make size of each block an integer
ptr=(int*)calloc(n,size);//calloc implementation for dynamic memory allocationif(ptr==NULL){
printf("Memory not allocated.n");
exit(0);
}
else{
//memory will be successfully allocated
printf("Memory successfully allocated using calloc function.n");
for(int i=0;i<n;++i){//assigning values created array
ptr[i]=i+1;
}
//printing the elements of an array
printf("The elements in the array ptr are:");
for(int i=0;i<n;++i){
printf("%d",ptr[i]);
}
}
return 0;
}
output
Memory successfully allocated using calloc function.
The elements in the array ptr are:12345
Process finished with exit code 0
RELEASING THE ALLOCATED SPACE:
FREE()
 The free() function is part of the stdlib.h header file.
 It deallocates the memory previous allocated by malloc(),
calloc() or realloc()
 General syntax:
free (ptr);
where ptr is a pointer to a memory block which has been
previously created using malloc
 Note that no size needs to be mentioned for the allocated
block, the system remembers it for each pointer returned
USAGE OF FREE
• The free function takes in a single argument
of the memory block to be freedr
• It does not return a value (returns void)
• Example free(ptr)
IMPORTANT CONSIDERATIONS
• Only pass a pointer returned by one of the dynamic memory allocations to free
• Do not attempt to free already freed memory (an error will occur or the
program crash
• Do not free memory that was not dynamically allocated
• Avoid using pointers after deallocating the associated memory
PREVENTING MEMORY LEAKS
• Proper use of free() helps prevent mamory leaks
• What are memory leaks?
• memory leaks occur when a computer fails to release memory that is no
longer needed resulting in gradual consumption of system resources
DIFFERENCES BETWEEN STATIC AND
DYNAMIC MEMORY
No Static Memory Allocation Dynamic Memory Allocation
1 The memory is allocated at compile
time
The memory is allocated at run time
2 While executing a program, the
memory cannot be changed.
While executing a program the memory
can be changed
3 Static memory allocation has a fixed
memory location
Dynamic memory allocation has no fixed
memory allocation
4 It saves running time as it is fast It is slower than static memory allocation
5 Static memory is preferred on an
array
Dynamic memory allocation is preferred
in linked list
(linked lists to be visited later)
6 The memory allocation is simple The memory allocation is complicated

More Related Content

Similar to final GROUP 4.pptx

Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresSelvaraj Seerangan
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTAkhilMishra50
 
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.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationGaurav Mandal
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationUTTAM VERMA
 
GLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingGLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingArun Kumar
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxNiharika606186
 
Dma
DmaDma
DmaAcad
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptxjack881
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptxAshirwad2
 

Similar to final GROUP 4.pptx (20)

Stack & heap
Stack & heap Stack & heap
Stack & heap
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
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.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
GLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingGLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meeting
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
aspice
aspiceaspice
aspice
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
C- language Lecture 6
C- language Lecture 6C- language Lecture 6
C- language Lecture 6
 
Dma
DmaDma
Dma
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
Pointer
PointerPointer
Pointer
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
 

Recently uploaded

Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 

Recently uploaded (20)

Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 

final GROUP 4.pptx

  • 1. DYNAMIC MEMORY ALLOCATION IN C BY GROUP 4 SOFTWARE ENGINEERING
  • 2. CONTENTS 1. Introduction to topic 2. Theory of dynamic memory allocation 3. Stdlib.h functions 4. Malloc 5. Calloc 6. Realloc 7. Free 8. Presentation of the code on an IDE 9. Difference between dynamic and static memory allocation 10. Summary
  • 3. WHAT IS ALLOCATION? AN ALLOCATION IS SOMETHING THAT YOU SET ASIDE FOR USE. FOR INSTANCE IF YOU WANT TO SET ASIDE A CERTAIN AMOUNT OF HARD DRIVE SPACE FOR AN APPLICATION. MEMORY ALLOCATION IS THE PROCESS OF SETTING ASIDE SECTION OF MEMORY IN A PROGRAM TO BE USED TO STORE VARIABLES, AND INSTANCES OF STRUCTURE AND CLASSES. INTRODUCTION
  • 4. WHAT IS DYNAMIC MEMORY ALLOCATION? Dynamic memory allocation in C is the process of allocating memory at runtime. Dynamic memory allocation is useful for creating data structures that need to be variable in size, such as arrays, linked lists, and trees.
  • 5.
  • 6. • Heap Allocation: The memory is allocated during the execution of instructions written by programmers. • It is called a heap because it is a pile of memory space available to programmers to allocate and de-allocate. • If a programmer does not handle this memory well, a memory leak can happen in the program. • Stack: allocates or de-allocates the memory automatically as soon as the corresponding method completes its execution.
  • 7. The term 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. Malloc allocates a contiguous block of memory. If enough contiguous memory is not available, then malloc returns NULL MALLOC
  • 8. MEMORY ALLOCATION CHECK  to make sure memory allocation was successful we use: void* p; if ((p=malloc(n)) == NULL) return 1; else { /* memory is allocated */}
  • 9. SYNTAX  size_t : stores only positive integer value, you can think of this particular datatype as unsigned integer datatype.  size cannot be negative , it can be either positive or zero value.  Malloc return a void pointer that gives us the address of the first byte in the block of memory that it allocates. void * malloc(size_t size);
  • 10. EXAMPLE void *malloc(2*sizeof(int)); //(no of elements * size of one unit) • this will store 2 * 4 = 8 byte on the memory say from address 201 to 208 ie. • It allocates a block of memory for array of 2 integer , each of 4 byte Value 1 Value 2 201 208 • so the malloc will return void ptr to the address of the first byte i.e 201. • if we want to store values at these addresses. • As malloc return void ptr, and void ptr cannot be de-referenced, so we cannot directly assign the values as *p = 2;void ptr can be typecasted into a pointer type of particular datatype and then it is used. • Inorder to use this block of memory we first need to typecast this void pointer of some datatype like thisSyntax : pointer = (type) malloc (size in bytes);
  • 11. EXAMPLE ptr=(int*)malloc(2*sizeof(int));//2*4=8bytes By asking memory block of 2 integers, we are basically creating an array of integers with 2 elements.
  • 12. Assigning values to the address : ptr = 2; // this will assign value at the address say 201 (ptr + 1) = 3; // this will assign value at the address 205
  • 15. CALLOC • It is used to allocate multiple block of requested memory with the same givenmemory size of memory for each block • it initializes all bytes to zero • It returns NULL if the memory is not sufficient
  • 16. SYNTAX void*calloc(size_t n, size_t size) ptr =(cast - type*)calloc(number,byte size); • Cast type - represents the data types that we are using for type casting • Number of block - number of blocks it will allocate / number of elements in the data type • Size of block- size of one single block / size of data type
  • 17. EXAMPLE ptr =(int*)calloc(n,size); ptr=(int*)calloc(n,sizeof(int)) ptr =(float*)calloc(25,sizeof(float)); // space is created for 25 elements eachof size of a float (4 bits)
  • 18. #include <stdio.h> #include <stdlib.h> int main() { int*ptr;//this pointer will hold the base address of created memory blocks int n=5;//Let say we have to create 5 blocks int size=sizeof(int);//lets say we want to make size of each block an integer ptr=(int*)calloc(n,size);//calloc implementation for dynamic memory allocationif(ptr==NULL){ printf("Memory not allocated.n"); exit(0); } else{ //memory will be successfully allocated printf("Memory successfully allocated using calloc function.n"); for(int i=0;i<n;++i){//assigning values created array ptr[i]=i+1; } //printing the elements of an array printf("The elements in the array ptr are:"); for(int i=0;i<n;++i){ printf("%d",ptr[i]); } } return 0; }
  • 19. output Memory successfully allocated using calloc function. The elements in the array ptr are:12345 Process finished with exit code 0
  • 20. RELEASING THE ALLOCATED SPACE: FREE()  The free() function is part of the stdlib.h header file.  It deallocates the memory previous allocated by malloc(), calloc() or realloc()  General syntax: free (ptr); where ptr is a pointer to a memory block which has been previously created using malloc  Note that no size needs to be mentioned for the allocated block, the system remembers it for each pointer returned
  • 21. USAGE OF FREE • The free function takes in a single argument of the memory block to be freedr • It does not return a value (returns void) • Example free(ptr)
  • 22. IMPORTANT CONSIDERATIONS • Only pass a pointer returned by one of the dynamic memory allocations to free • Do not attempt to free already freed memory (an error will occur or the program crash • Do not free memory that was not dynamically allocated • Avoid using pointers after deallocating the associated memory
  • 23. PREVENTING MEMORY LEAKS • Proper use of free() helps prevent mamory leaks • What are memory leaks? • memory leaks occur when a computer fails to release memory that is no longer needed resulting in gradual consumption of system resources
  • 24. DIFFERENCES BETWEEN STATIC AND DYNAMIC MEMORY No Static Memory Allocation Dynamic Memory Allocation 1 The memory is allocated at compile time The memory is allocated at run time 2 While executing a program, the memory cannot be changed. While executing a program the memory can be changed 3 Static memory allocation has a fixed memory location Dynamic memory allocation has no fixed memory allocation 4 It saves running time as it is fast It is slower than static memory allocation 5 Static memory is preferred on an array Dynamic memory allocation is preferred in linked list (linked lists to be visited later) 6 The memory allocation is simple The memory allocation is complicated