Dynamic Memory
Dynamic Memory
MANAGEMENT –
DYNAMIC MEMORY
ALLOCATION
Memory Allocation in C :
It is the procedure to allocate memory cells to the variables.
There are two memory allocation methods. They are,
1. Static memory allocation
2. Dynamic memory allocation
When a variable is declared compiler automatically
allocates memory for it.
This is known as compile time memory allocation or
static memory allocation.
Memory can be allocated for data variables after the
program begins execution.
This mechanism is known as runtime memory
allocation or dynamic memory allocation.
Static Memory Allocation:
The process of allocating memory space at compile time is
known as static memory allocation. In static memory allocation
size is fixed.
Example: Arrays int a[5];
The above declaration of an array allocates spaces for storing 5
integer data in the memory.
Static Memory allocation has the following Disadvantages:
• Size is not expandable
• Insertion is difficult(Time consuming process) o It requires a
lot of data movement taking more time.
• Deletion is also difficult.
Dynamic Memory Allocation:
The process of allocating memory space at run time known as dynamic
memory allocation. In dynamic memory allocation size (no of cells is not
allocated) is not fixed.
Example: Linked List
Linked List: A linked list is collection of more than one nodes linked
together. Each node has an element.
A linked list has the following characteristics
• To store each element, we use a node.
• A node consists of data (elements) and link field.
• If there is only one link field, it is called as singly linked list.
• If it has 2 links, it is doubly linked list.
• The nodes need not be stored continuously in the memory.
The advantages of linked list are
• Size is not fixed.
• Insertion is easy which does not require any data movement.
• Deletion is also easy.
Dynamic Memory Allocation Functions:
malloc()
calloc()
sizeof()
free()
realloc()
DMA predefined functions are available in c library.
These are used to allocating and reallocating the memory space in
memory.
DMA functions are available through the header file is stdlib.h and
alloc.h
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,
•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.
malloc() method
“malloc” or “memory allocation” method in C is used to
dynamically allocate a single large block of memory with the
specified size.
It returns a pointer of type void which can be cast into a pointer
of any form.
It initializes each block with default garbage value.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25
elements each with the size of the float.
If space is insufficient, allocation fails and returns a
NULL pointer.
//example program for calloc function
#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: %d\n", 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
printf("Enter the Elements of the array\n"); OUTPUT
for (i = 0; i < n; ++i)
{
scanf("%d",&ptr[i]);
}
// 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.
Syntax:
free(ptr);
// Program to calculate the sum of n numbers entered by
the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: \n");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum); OUTPUT:
free(ptr);
printf("The Elements are:\n");
{
for(i=0;i<n;i++)
{
printf("%d\n",ptr);
}
}
return 0;
}
//EXAMPLE PROGRAM FOR FREE() FUNCTION
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *numbers = (int*)malloc(4* sizeof(int));
OUTPUT:
int i;
numbers[0] = 10;
numbers[1] = 20;
free(numbers);
printf("\nStored integers are ");
for(i = 0; i < 2; i++)
printf("\numbers[%d] = %d ", i, numbers[i]);
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:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size
'newSize'.
If space is insufficient, allocation fails and returns a NULL
pointer.
// EXAMPLE PROGRAM FOR REALLOC FUNCTION
#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: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(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 {
free(ptr);
}
return 0;
}
THANK YOU