Chapter 11 - Dynamic Memory Management
Chapter 11 - Dynamic Memory Management
◼ Programming Examples
◼ Assignments
➢ So far, in all our programs, the variables are allocated with memory
space at compilation time.
➢ However, in some programming situations (particularly when dynamic
storage is required with structures like arrays, linked-lists, stacks, queues etc.) this
way of memory allocation may not be efficient as it may cause wastage
of memory space or failure of the program (due to memory overflow).
For example, let us consider a string “name” that intends to store the
name of a person in a program. When we declare the string as:
char name[10];
◼ During program execution (i.e., at runtime), when we need some memory space
(to be allocated to some variable), a program called the “memory manager” is
invoked (through some pre-defined functions) to allocate memory. The memory
manager searches the heap segment for the requested amount of space. There
are three methods of searching:
➢ First-fit: Allocate the first space that is big enough.
➢ Best-fit: Allocate the smallest space that is big enough.
➢ Worst-fit: Allocate the largest space that is big enough.
If the required space is available, it is given, otherwise the memory manager
indicates “memory overflow” by returning a NULL.
Syntax:
ptr = (cast_type*)malloc(byte_size);
/* “ptr” is a pointer of type “cast_type”. */
◼ calloc(): It allocates the requested size of bytes, initializes them to zero, and
then returns a pointer of type void to the first byte of the allocated space. If it
fails to allocate, it returns NULL.
Syntax:
ptr = (cast_type*)calloc(n, element_size);
/* “ptr” is a pointer of type “cast_type”. */
Syntax:
Syntax:
free(ptr);
/* “ptr” points to a previously allocated memory space. */
/* PR11_1.c: Program that stores ‘n’ integers (the value of ‘n’ is specified at runtime) in an array and
displays them in reverse order . */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
void main()
{
int size, *numArray, *i;
printf("\nHow many integers do you want to enter?: ");
scanf("%d", &size);
/* Allocating Memory */
numArray = (int *)malloc(size * sizeof(int));
if(numArray == NULL)
{
printf("No space available.");
exit(1);
}
printf("Space allocated for %d integers.", size); [Cont.]
getch();
}
Output
Enter 5 integers: 1 3 5 7 9
The numbers in the reverse order are: 9 7 5 3 1
/* PR11_2.c: Write a program to store a word in a string whose size is determined by the user at
runtime and then modify the same to store a larger word. */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
void main()
{
int size;
char *word;
printf("\nEnter the size of the word: ");
scanf("%d", &size);
/* Allocating Memory */
word = (char *)calloc(size, sizeof(char));
if(word == NULL)
{
printf("No space available.");
exit(1);
}
printf("Space allocated for a %d lettered word.", size);
[Cont.]
/* Freeing memory */
free(word);
getch();
}
Output
Reallocating memory...