Memory allocation is the process of setting aside sections of memory in a program to be used to store variables, and instances of structures and classes.
There are two types of memory allocations possible in C:
int x, y; float a[5];
When the first statement is encountered, the compiler will allocate two bytes to each variables x and y. The second statement results into the allocction of 20 bytes to the array a (5*4, where there are five elements and each element of float type tales four bytes). Note that as there is no bound checking in C for array boundaries, i.e., if you have declared an array of five elements, as above and by mistake you are intending to read more than five values in the array a, it will still work without error. For example you are reading the above array as follows :
for ( i = 0 ; i < 10 ; i++) { scanf ("%d", &a[i]); }
C provides the following dynamic allocation and de-allocation functions :
The Malloc( ) Function
The malloc( ) function allocates a block of memory in bytes. The user should explicitly give the block sixe it requires of the use. The malloc( ) is like a request to the RAM of the system to allocate memoty.
Syntax:-
malloc (number of elements * size of each element) ;
Example:-
int *ptr ; ptr = malloc (10 *sizeof(int))
This function works exactly similar to malloc( ) function except for the fact that it needs two arguments as against one argument required by malloc( ).
Example:-
int *ptr ; ptr = (int *) calloc (10, 2);
The Free( ) Function
The free( ) function is used to de-allocate the previously allocated memory using malloc( ) or calloc( ) functions.
Syntax:-
free (ptr_var); // Where ptr_var is the pointer in which the address of the allocated memory block is assigned.
The Realloc( ) Function
This function is used to resize the size of memory block, which is already allocated. It found use of in two situations :
Syntax:-
ptr_var = realloc (ptr_var, new_size);