C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many language permit a programmer to specify an array’s size at run time. Such languages have the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation.
Allocating a Block of Memory
A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. General syntax is
ptr = (cast_type*) malloc (byte-size);
ptr is a pointer of type cast_type. The malloc returns a pointer (of cast_type) to an area of memory with size byte_size. Example:
x = (int*) malloc (100*sizeof(int));
On successful execution of this statement, a memory space equivalent to “100 times the size of and int” bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type of int.
Releasing the used space
When we no longer need the data we stored in a block of memory, and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function: