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 *) This statement returns a pointer to size_in_bytes of
malloc (size_in_bytes); uninitialized storage, or NULL if the request cannot be
satisfied.
Example: fp = (int *)malloc(sizeof(int)
*20);
Example ::
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(Pointer1.c)
#include <stdio.h>
#include <stdlib.h> else {
int main() // Memory has been successfully allocated
{
printf("Memory successfully allocated
// This pointer will hold the using malloc.\n");
// base address of the block created
int* ptr; // Get the elements of the array
int n, i; for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
// Get the number of elements for the array }
n = 5;
printf("Enter number of elements: %d\n", n); // Print the elements of the array
// Dynamically allocate memory using malloc() printf("The elements of the array are:
ptr = (int*)malloc(n * sizeof(int)); ");
for (i = 0; i < n; ++i) {
// Check if the memory has been successfully printf("%d, ", ptr[i]);
// allocated by malloc or not }
if (ptr == NULL) { }
printf("Memory not allocated.\n"); return 0;
exit(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 *) This statement returns a pointer to no_of_blocks of
calloc (no_of_blocks, size size_of_blocks, it returns NULL if the request
size_of_block); cannot be satisfied.
Example:
int n = 20;
fp = (int *)calloc(n, sizeof(int));
Example ::
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of
the float.
Example(calloc1.c)
#include <stdio.h>
#include <stdlib.h> else {
int main() // Memory has been successfully
{ allocated
printf("Memory successfully allocated
// This pointer will hold the using calloc.\n");
// base address of the block created
int* ptr; // Get the elements of the array
int n, i; for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
// Get the number of elements for the array }
n = 5;
printf("Enter number of elements: %d\n", n); // Print the elements of the array
printf("The elements of the array
// Dynamically allocate memory using are: ");
calloc() for (i = 0; i < n; ++i) {
ptr = (int*)calloc(n, sizeof(int)); printf("%d, ", ptr[i]);
}
// Check if the memory has been successfully }
// allocated by calloc or not
if (ptr == NULL) { return 0;
printf("Memory not allocated.\n");
exit(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(free1.c)
#include <stdio.h>
#include <stdlib.h> else {
int main() // Memory has been successfully
{ allocated
printf("Memory successfully allocated
// This pointer will hold the using malloc.\n");
// base address of the block created
int *ptr, *ptr1; // Free the memory
int n, i; free(ptr);
printf("Malloc Memory successfully
// Get the number of elements for the array freed.\n");
n = 5;
printf("Enter number of elements: %d\n", n); // Memory has been successfully
allocated
// Dynamically allocate memory using printf("\nMemory successfully
malloc() allocated using calloc.\n");
ptr = (int*)malloc(n * sizeof(int));
// Free the memory
// Dynamically allocate memory using free(ptr1);
calloc() printf("Calloc Memory successfully
ptr1 = (int*)calloc(n, sizeof(int)); freed.\n");
}
// Check if the memory has been successfully
// allocated by malloc or not return 0;
if (ptr == NULL || ptr1 == NULL) { }
printf("Memory not allocated.\n");
exit(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 *) This statement returns a pointer to new space, or NULL if
realloc (void *fp, the request cannot be satisfied.
size_t);
Example:
fp = (int *)realloc(fp,sizeof(int)*20);
realloc() method
Example ::
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
Example::
▪ Example:: relloc1.c
▪ Write a C program to sort numbers using malloc.