Consider an example of students progress report (for the sake of simplicity). The number of students are different in different classes. There fore, we have to read the number of students from the user (data entry operator). For each student, we need an integer for register number, a few integers to store scores in subjects, a few characters to store address and so on. In this case, the total amount of memory needed depends on the number of students in a class. There fore, the amount of memory that should be allocated for the program should be decided based on the input. In such cases we use dynamic memory allocation.
C programming language allows dynamic memory allocation. Most of modern programming languages use dynamic memory allocation. Java is an example. Unlike C, there is not a concept of pointers in Java because all variables are actually pointers.
Functions for Dynamic Memory Allocation in C
The functions used for dynamic memory allocation or deallocation are malloc, realloc, calloc and free. These functions are defined in the header file stdlib.h- malloc
- This function is used to allocated specified number of bytes.
- realloc
- Used to increase or decrease size of a block of memory. Allocation or Deallocation of bytes is performed if necessary.
- calloc
- Allocates specified number of bytes and also intialises all bytes to zero. This function allows to specify how many blocks of specified size should be allocated.
- free
- Deallocates and releases the specified block of memory.
Malloc function
First, we will see the syntax of malloc function. Then it will be easier to explain. Syntax is as follows:void * malloc(int sizeInBytes);
The above shown prototype of malloc function tells that it always return a pointer to 'void' data type. That is, the pointer can be type-casted to int pointer, char pointer or to any other data type. malloc functions takes a parameter which is the amount of memory (number of bytes) to be allocated. It is recommended to specify the size using sizeof operator. We will see a few examples of dynamic memory allocation using malloc function.
int *p=malloc(10*sizeof(char));
- Allocates memory to accommodate 10 characters.
int *p=malloc(20*sizeof(int));
- Allocates memory to accommodate 20 integers.
int *p=malloc(sizeof(float));
- Allocates memory to accommodate a float.
int *p=malloc(10*sizeof(struct student));
- Allocates memory to accommodate 10 instances of structure named student. This is how to store derived datatypes (user defined data types) like structures dynamically in c.
Realloc Function
Realloc function is used either to shrink or to expand an already allocated memory. It is called after allocation of memory using malloc or calloc function. Suppose we initially allocated memory for 10000 characters dynamically. Later, during the of execution of program, we find that only 5000 characters need to be stored. Therefore, we are not going to use the rest. To avoid memory wastage, we may deallocate the remaining 5000 character spaces trailing being the used 5000. The following code will shrink the initially allocated 10000 chars to 5000 chars by deallocating the remaining.void * realloc(void *pointer,size_t size)
The first parameter pointer is the pointer to the memory block allocated earlier. The next argument size is the new (updated) size. It size is greater than the older size, additional memory will be allocated to get size number of bytes allocated in total. If it is less than older size, a part of memory will be deallocated which is equal to the difference between initial size and new size. If first parameter is NULL, a fresh block with specified size will be allocated.
char *ptr; //Initial allocation ptr = (char *) malloc(150); //Reallocating memory to 50 char ptr = (char *) realloc(ptr, 50);
Calloc Function
Calloc function is not much significantly different from malloc. The differences between malloc and calloc are:
- Calloc lets you to specify the number of variables (of same data type) and space needed by each data type by taking two parameters.
- When allocated using malloc, the memory block may contain junk data (garbage values) but calloc initializes every allocated byte to zero.
The following code fragment shows example use of calloc with structure:
#include<stdlib.h> struct student { int rollno; char name[30]; }; int main() { struct student *list,*temp; list=(struct student *)calloc(5,sizeof(struct student)); for(temp=list;temp-list<5;temp++) { printf("Enter roll number and name of student\n"); scanf("%d%s",&temp->rollno,&temp->name); } printf("\nThe students are:\n"); for(temp=list;temp-list<5;temp++) { printf("Roll number: %d Name: %s\n",temp->rollno,temp->name); }
free(list);
return 0; }
Output
Enter roll number and name of student 1 matthew Enter roll number and name of student 2 mathews Enter roll number and name of student 3 shareef Enter roll number and name of student 4 muneer Enter roll number and name of student 5
nihal The students are: Roll number: 1 Name: matthew Roll number: 2 Name: mathews Roll number: 3 Name: shareef Roll number: 4 Name: muneer Roll number: 5 Name: nihal
In the above example a structure named student is used. Each structure variable has a roll number and name. Memory to store for 5 student structure variables are allocated using calloc. The pointer arithmetic for pointers to structures is also demonstrated in above program.
Free Function
The free function is used to free (deallocate) an already allocated block of memory. When your program no longer needs the dynamically allocated block of memory, the free function should be called to return the memory occupied to the free store. In the above example program, the following line of code deallocated the allocated block of memory.
free(list);
The free function takes the pointer to the block of memory which is allocated dynamically as parameter and frees or deallocates the block so that it can be used later.