Unit 9 Dynamic Memory Allocation
Unit 9 Dynamic Memory Allocation
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.
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 {
// 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) { }
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 {
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 ::