Dynamic memory allocation in C and C++

Dynamic memory allocation just means allocating memory dynamically by the programmer, that means the programmer can allocate memory on the basis of need and requirements, which also needs to be deallocated by the programmer only( With great powers comes great responsibilities ), unlike normal allocation of memory to the variables by the compiler in which the allocation and deallocation process are automatic and the programmer need not worry about them.
So now that we have understood what is dynamic memory allocation, the question arises that how to do it.
Well there are three ways as far as I know, first one and the most common one being using malloc function for allocating memory directly from the heap, secondly we can also use new and delete operator, and lastly we can use get_temporary_memory() function which I didn't knew from before.
The most preferred way is using new and delete operators which allocates memory from free storage.
It is preferred over malloc function because malloc doesn't call constructors, and also cause in malloc we have to specify the size of the memory beforehand only, whereas in new the size of the memory is calculated automatically by the compiler. Also, the new operator, if there isn'r enough memory for allocation, it returns bad_alloc exception which we can resolve using the dethrow with the syntax of  new.
Like int* ptr = new int(12); Here I also initiliazed the variable pointer which we couldn't have done during the initialization process while using malloc.
We use free(), for deallocation of memory with malloc function and with new operator we use delete.
While with get_temporary_memory() we use return_temporary_memory() which is quite logical.

Comments

Popular Posts