Dynamic Memory
Dynamic Memory
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.
• 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 program else
#include <stdio.h> {
#include <stdlib.h> printf("Memory allocation is successful.");
int main() for (i = 0; i < n; ++i)
{ ptr[i] = i + 1;
printf(“Array elements are: ");
int* ptr;
for (i = 0; i < n; ++i)
int n=5, i;
printf("%d, ", ptr[i]);
printf("Enter number of elements: %d", n);
}
ptr = (int*)malloc(n * sizeof(int));
return 0;
if (ptr == NULL) }
{
printf("Memory not allocated.\n");
exit(0);
calloc() or contiguous allocation
• Method in C is used to dynamically allocate multiple blocks of memory,
the specified number of blocks of memory of the specified type.
• p = (int*)realloc(ptr, n*sizeof(int));
• realloc deallocates the old object pointed to by ptr and returns a pointer to a new object
that has the size specified.
• The contents of the new object is identical to that of the old object prior to deallocation,
up to the lesser of the new and old sizes.
• Any bytes in the new object beyond the size of the old object have
indeterminate values.
Example program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i;
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
getchar();
return 0;
Free method
• “free” method in C is used to dynamically de-allocate the memory
previously allocated by malloc() and calloc(), since it is not de-allocated on
their own.
• Syntax: free(ptr);
Example program
#include <stdio.h>
else
#include <stdlib.h> {
int main() printf("Malloc Allocation is Success");
{ int *ptr, *ptr1, int n, i; free(ptr);
printf("Enter number of elements: printf("Malloc Memory successfully freed.");
%d", n); printf("Calloc Allocation is Success.");
ptr = (int*)malloc(n * sizeof(int)); free(ptr1);
ptr1 = (int*)calloc(n, sizeof(int)); printf(“Calloc Memory successfully freed.");
if (ptr == NULL || ptr1 == NULL) }
return 0;
{ printf("Memory not
allocated.\n"); }
exit(0);
}
Difference between static and
dynamic memory allocation