Since the name of the array actually indicates the base address of the array of the address of the first element of the array, it is possible to define the array as a pointer rather than the conventional array. Logically, these two definitions of array are equivalent. However, a conventional array definition allocates a fixed block of memory being reserved at the time of the beginning of the program execution, whereas this does not happen in pointer representation of the array. The use of pointer representation of array requires some initial memory allocation before processing the array element. This is known as dynamic memory allocation.
The two main functions that are available for dynamic memory allocation in C are malloc () and calloc (). These functions are meant to allocate memory based upon the memory size requested. The malloc () function allocate the memory without clearing the bytes, by keeping the byte value prior to allocation, whereas the calloc () function clears all the allocated memory assigning zeroes into each byte. The general format for using malloc () function is as follows:
(casting _type *) malloc (size of data item);
For example, a block of memory will be allocated for 25 elements of integer type, and then following statements are to be declared.
int*ptr;
ptr = (int *) malloc (25*sizeof (int));
In this the base address will be stored in pointer variable ptr.
Whenever the function malloc () and calloc() are invoked, conditional test is performed on the pointer which has been allocated, the pointer will hold the address of the allocated memory block.
To free the block of memory, which was allocated by ither malloc () or calloc () function, free () function is used to release the memory. The general form of the free () function is given below:
Free (ptr);
where ptr is the pointer to the block of memory.
Include the following
Dynamically obtained memory can only be accessed with pointers. All dynamically allocated memory should be freed before program terminates, ideally as soon as possible to avoid memory “leaks”. Due to overhead with each allocated object, it may be better obtain a large block of memory and suballocate it as needed (such as for linked – list processing).
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc