We will ask the user how many memory blocks need to be allocated, and we will dynamically allocate that number of memory blocks. The user will then be asked to assign integer values to those memory blocks. After that, the user will be asked how many more additional blocks need to be allocated. Similarly, the user will be asked how many memory blocks need to be reduced too. The following are the steps to be performed in order to dynamically allocate memory, by increasing and decreasing memory blocks:
- The user is asked to enter an integer value, and that number of memory blocks will be dynamically allocated by invoking the calloc function. Each allocated memory block will be capable of storing a numerical of the integer data type.
- The user is then asked to enter values in the dynamically allocated memory blocks.
- Display the integer values on the screen that are assigned to the memory blocks.
- Ask the user how many more memory blocks need to be added.
- Invoke the realloc function to increase the number of allocated memory blocks.
- Ask the user to enter the integer values in the newly added memory blocks.
- Display all the integer values assigned to the memory blocks.
- Ask the user how many of the available memory blocks are required.
- Again, invoke the realloc function to reduce the number of allocated memory blocks.
- Display the integer values available in the existing memory blocks.
- Free up all of the memory blocks so that they can be used by other applications.
The program for showing the benefits of dynamic memory allocation, that is, how the memory can be allocated at runtime, and how its size can be increased or decreased and is freed, is as follows (dynamicmem.c):
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int m,n, i;
printf("How many elements are there? ");
scanf("%d", &n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory could not be allocated.\n");
exit(0);
}
printf("Enter %d elements \n", n);
for (i = 0; i < n; ++i)
scanf("%d",&ptr[i]);
printf("\nThe elements entered are: \n");
for (i = 0; i < n; ++i)
printf("%d\n", ptr[i]);
printf("\nHow many elements you want to add more? ");
scanf("%d",&m);
ptr = realloc(ptr, (m+n) * sizeof(int));
printf("Enter values for %d elements\n",m);
for (i = n; i < (m+n); ++i)
scanf("%d",&ptr[i]);
printf("\nThe complete set of elements now are: \n");
for (i = 0; i < (m+n); ++i)
printf("%d\n", ptr[i]);
printf("\nHow many elements you want to keep ? ");
scanf("%d", &m);
ptr = realloc(ptr, (m) * sizeof(int));
printf("\nThe new set of elements now are: \n");
for (i = 0; i < m; ++i)
printf("%d\n", ptr[i]);
free(ptr);
return 0;
}
Now, let's go behind the scenes to understand the code better.