C++ Tutorial

What is Dynamic Memory Allocation?

Dynamic memory allocation is the process of memory management in a program at runtime with the help of some defined keywords ( new/delete ). Honestly speaking, this is one of the fascinating concepts in the programming world if you can just feel it.

What is the purpose of Dynamic Memory Allocation?

In programming, the memory spaces needed are allocated before the execution of the program by declaring necessary variables. But there may be some scenarios where the memory spaces are needed to be defined or allocated at runtime rather than compile time. For example, there may be cases where a variable size needs to defined by the user at runtime.

How to use it?

C++ introduces new and delete keywords to hold memory allocation dynamically in programs.

pointer = new variable-type;
pointer = new variable-type[size];

We use new keyword in order to request dynamic memory allocation. The new keyword returns the address of the beginning new block of requested memory of the variable-type (data type specifier). Then assign it to the pointer variable for further use. If more than one memory block (ex: array) is required than the required size is declared with [ ] brackets.

The space of the Dynamically allocated memory doesn’t get freed automatically [it’s created on the heap] hence, it’s must be deallocated. To free the allocated memory space, we need to use delete keyword for the above allocation.

delete pointer;
delete [] pointer;

Application of Dynamic Memory Allocation

Well, there are lots of applications of Dynamic Memory Allocation. Here, I’m going to tell you briefly about beginner level application. This will help you to start your journey with dynamic memory allocation with clear intuition.

Have you ever wondered? Why you can’t use a variable for an array size instead of constants! Dynamic memory allocation can solve this problem easily.

Moreover, sometimes we need to keep a copy of some contents (values) for further use in our programs, i.e. from one function to another function. But unfortunately, after executing a block of function, the values of the variables are lost. That’s where allocating the memory dynamically is necessary.

Didn’t catch the scenario? Let’s take a look at this article, A brief intuition about dynamic memory allocationHope this will give you a great intuition about the concept more deeply.

If you have any confusion about the discussed topic please let me know. Feel free to comment & share your thoughts.

3 COMMENTS

Leave a Reply to A brief intuition about dynamic memory allocation – HeapNeverFlow Cancel reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.