SlideShare a Scribd company logo
Unit-9 Dynamic Memory
Allocation
1
Dynamic Memory Allocation (DMA)
 Since C is a structured language, it has some fixed rules for
programming.
 One of it includes changing the size of an array. An array is
collection of items stored at continuous memory locations.
 As it can be seen that the length (size) of the array above made is
9. But what if there is a requirement to change this length (size).
For Example,
Dynamic Memory Allocation (DMA)
 If there is a situation where only 5 elements are needed to be
entered in this array. In this case, the remaining 4 indices are just
wasting memory in this array. So there is a requirement to lessen
the length (size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with
all 9 indices filled. But there is a need to enter 3 more elements in
this array. In this case 3 indices more are required. So the length
(size) of the array needs to be changed from 9 to 12.
 This procedure is referred to as Dynamic Memory Allocation in C.
Dynamic Memory Allocation (DMA)
 Therefore, C Dynamic Memory Allocation can be defined as a
procedure in which the size of a data structure (like Array) is
changed during the runtime.
 C provides some functions to achieve these tasks. There are 4
library functions provided by C defined under <stdlib.h> header
file to facilitate dynamic memory allocation in C programming.
They are:
• malloc()
• calloc()
• free()
• realloc()
Dynamic Memory Allocation (DMA)
 If memory is allocated at runtime (during execution of program)
then it is called dynamic memory.
 It allocates memory from heap (heap: it is an empty area in
memory)
 Memory can be accessed only through a pointer.
When DMA is needed?
 It is used when number of variables are not known in advance or
large in size.
 Memory can be allocated at any time and can be released at any
time during runtime.
malloc() function
 malloc () is used to allocate a fixed amount of memory during
the execution of a program.
 malloc () allocates size_in_bytes of memory from heap,
if the allocation succeeds, a pointer to the block of memory is
returned else NULL is returned.
 Allocated memory space may not be contiguous.
 Each block contains a size, a pointer to the next block, and the
space itself.
 The blocks are kept in ascending order of storage address, and the
last block points to the first.
 The memory is not initialized. It initializes each block with default
garbage value.
malloc() function
Syntax Description
ptr_var = (cast_type *
) malloc
(size_in_bytes);
This statement returns a pointer to size_in_bytes
of uninitialized storage, or NULL if the request cannot be
satisfied.
Example: fp = (int *)malloc(sizeof(int)
*20);
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.
Example ::
Example(Pointer1.c)
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using
malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully
allocated using malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array
are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
calloc() function
 “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory of
the specified type.
 calloc() allocates a region of memory to hold
no_of_blocks of size_of_block each, if the allocation
succeeds then a pointer to the block of memory is returned else
NULL is returned.
 It initializes each block with a default value ‘0’.
calloc() function
Syntax Description
ptr_var = (cast_type *
) calloc
(no_of_blocks,
size_of_block);
This statement returns a pointer to no_of_blocks of
size size_of_blocks, it returns NULL if the request
cannot be satisfied.
Example:
int n = 20;
fp = (int *)calloc(n, sizeof(int));
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size
of the float.
Example ::
Example(calloc1.c)
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the
array
n = 5;
printf("Enter number of elements: %dn",
n);
// Dynamically allocate memory using
calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been
successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully
allocated
printf("Memory successfully
allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the
array
printf("The elements of the array
are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
free() method
 “free” method in C is used to dynamically de-allocate the
memory.
 The memory allocated using functions malloc() and calloc() is not
de-allocated on their own.
 Hence the free() method is used, whenever the dynamic memory
allocation takes place.
 It helps to reduce wastage of memory by freeing it.
free() method
 Syntax::
• free(ptr);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the
array
n = 5;
printf("Enter number of elements: %dn",
n);
// Dynamically allocate memory using
malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using
calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been
successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
else {
// Memory has been successfully
allocated
printf("Memory successfully
allocated using malloc.n");
// Free the memory
free(ptr);
printf("Malloc Memory
successfully freed.n");
// Memory has been successfully
allocated
printf("nMemory successfully
allocated using calloc.n");
// Free the memory
free(ptr1);
printf("Calloc Memory
successfully freed.n");
}
return 0;
}
realloc() method
 “realloc” or “re-allocation” method in C is used to dynamically
change the memory allocation of a previously allocated memory.
 In other words, if the memory previously allocated with the help
of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.
 re-allocation of memory maintains the already present value and
new blocks will be initialized with default garbage value.
Syntax Description
ptr_var = (cast_type
*) realloc (void *fp,
size_t);
This statement returns a pointer to new space, or NULL if
the request cannot be satisfied.
Example:
fp = (int *)realloc(fp,sizeof(int)*20);
Example ::
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
realloc() method
Ad

More Related Content

Similar to CLanguage_ClassPPT_3110003_unit 9Material.ppt (20)

Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
babuk110
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
Shajahan T S Shah
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
data structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptxdata structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptx
sandeepg77
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
웅식 전
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
BilalImran17
 
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
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
Niharika606186
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
UTTAM VERMA
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
baabtra.com - No. 1 supplier of quality freshers
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
Dma
DmaDma
Dma
Acad
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
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
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
ngonidzashemutsipa
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
babuk110
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
data structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptxdata structure notes for engineering DSA3.pptx
data structure notes for engineering DSA3.pptx
sandeepg77
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
웅식 전
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
BilalImran17
 
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
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
Niharika606186
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
UTTAM VERMA
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
Dma
DmaDma
Dma
Acad
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
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
 

Recently uploaded (20)

Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
AI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in RetailAI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in Retail
IJDKP
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Environment .................................
Environment .................................Environment .................................
Environment .................................
shadyozq9
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
ijdmsjournal
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
AI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in RetailAI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in Retail
IJDKP
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Environment .................................
Environment .................................Environment .................................
Environment .................................
shadyozq9
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
ijdmsjournal
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Ad

CLanguage_ClassPPT_3110003_unit 9Material.ppt

  • 2. Dynamic Memory Allocation (DMA)  Since C is a structured language, it has some fixed rules for programming.  One of it includes changing the size of an array. An array is collection of items stored at continuous memory locations.  As it can be seen that the length (size) of the array above made is 9. But what if there is a requirement to change this length (size). For Example,
  • 3. Dynamic Memory Allocation (DMA)  If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5.  Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.  This procedure is referred to as Dynamic Memory Allocation in C.
  • 4. Dynamic Memory Allocation (DMA)  Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.  C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: • malloc() • calloc() • free() • realloc()
  • 5. Dynamic Memory Allocation (DMA)  If memory is allocated at runtime (during execution of program) then it is called dynamic memory.  It allocates memory from heap (heap: it is an empty area in memory)  Memory can be accessed only through a pointer. When DMA is needed?  It is used when number of variables are not known in advance or large in size.  Memory can be allocated at any time and can be released at any time during runtime.
  • 6. malloc() function  malloc () is used to allocate a fixed amount of memory during the execution of a program.  malloc () allocates size_in_bytes of memory from heap, if the allocation succeeds, a pointer to the block of memory is returned else NULL is returned.  Allocated memory space may not be contiguous.  Each block contains a size, a pointer to the next block, and the space itself.  The blocks are kept in ascending order of storage address, and the last block points to the first.  The memory is not initialized. It initializes each block with default garbage value.
  • 7. malloc() function Syntax Description ptr_var = (cast_type * ) malloc (size_in_bytes); This statement returns a pointer to size_in_bytes of uninitialized storage, or NULL if the request cannot be satisfied. Example: fp = (int *)malloc(sizeof(int) *20); ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. Example ::
  • 8. Example(Pointer1.c) #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 9. calloc() function  “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type.  calloc() allocates a region of memory to hold no_of_blocks of size_of_block each, if the allocation succeeds then a pointer to the block of memory is returned else NULL is returned.  It initializes each block with a default value ‘0’.
  • 10. calloc() function Syntax Description ptr_var = (cast_type * ) calloc (no_of_blocks, size_of_block); This statement returns a pointer to no_of_blocks of size size_of_blocks, it returns NULL if the request cannot be satisfied. Example: int n = 20; fp = (int *)calloc(n, sizeof(int)); ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float. Example ::
  • 11. Example(calloc1.c) #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by calloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using calloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0;
  • 12. free() method  “free” method in C is used to dynamically de-allocate the memory.  The memory allocated using functions malloc() and calloc() is not de-allocated on their own.  Hence the free() method is used, whenever the dynamic memory allocation takes place.  It helps to reduce wastage of memory by freeing it.
  • 14. Example #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int *ptr, *ptr1; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using calloc() ptr1 = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL || ptr1 == NULL) { else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.n"); // Free the memory free(ptr); printf("Malloc Memory successfully freed.n"); // Memory has been successfully allocated printf("nMemory successfully allocated using calloc.n"); // Free the memory free(ptr1); printf("Calloc Memory successfully freed.n"); } return 0; }
  • 15. realloc() method  “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.  In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.  re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value. Syntax Description ptr_var = (cast_type *) realloc (void *fp, size_t); This statement returns a pointer to new space, or NULL if the request cannot be satisfied. Example: fp = (int *)realloc(fp,sizeof(int)*20);
  • 16. Example :: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'. realloc() method
  翻译: