Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
Dynamic Memory Allocation In C++ is a very important feature that lets you consider your requirements to deal with the need for real time resources. In this article we would be exploring Dynamic memory Exploration in detail. Following Pointers will be covered in this article,
So let us get started with this article on Dynamic Memory Allocation in C++
Let say, we want to input a sentence as an array of characters but we are not sure about the exact number of characters required in the array.
Now, while declaring the character array, if we specify its size smaller than the size of the desired string, then we will get an error because the space in the memory allocated to the array is lesser compared to the size of the input string. If we specify its size larger than the size of the input string, then the array will be allocated a space in the memory which is much larger than the size of the desired string, thus unnecessarily consuming more memory even when it is not required.
In the above case, we don’t have the idea about the exact size of the array until the compile-time (when computer compiles the code and the string is input by the user). In such cases, we use the new operator.
C++ defines two unary operators new and delete that perform the task of allocating and deallocating memory during runtime. Since these operators (new and delete) operate upon free store memory (Heap memory), they are also called free store operator. Pointers provide the necessary support for dynamic memory allocation system in C++.
With the help of Dynamic Allocation, a program can obtain memory during runtime.
The global and local variables are allocated to memory during compile-time. However, we cannot add any global or local variables during runtime. If the program needs to use a variable amount of memory we would need to allocate memory during runtime, as and when needed. And of course, here the dynamic allocation routines can serve the purpose.
Differences between Static memory allocation and Dynamic memory allocation:
This is a basic memory architecture used for any C++ program:
We will need a image like this
The stack is used for static memory allocation and Heap for dynamic memory allocation, both are stored in the computer’s RAM.
Variables that get allocated on the stack while static memory allocation is stored directly to the memory and access to this memory is very fast, also its allocation is dealt with when the program is compiled. When a function or a method calls another function which might in turn calls another function and so on, the execution of all these functions remains suspended until the very last function returns its value. The stack is always stored in a LIFO(last in first out) order, the most recently reserved block is always the next block to be freed. This helps to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.
Variables allocated on the heap have their memory allocated at run time while dynamic memory allocation. Accessing this memory is a bit slower as compared to stack, but the size of the heap is only limited by the size of virtual memory. The element of the heap has no dependencies with each other and can always be accessed randomly at any moment of time. We can allocate a block at any time and free it at any time. This makes it difficult to keep track of which parts of the heap are allocated or deallocated at any given time.
Moving on with this article on Dynamic Memory Allocation in C++
In C++ the new operator is used to allocate memory at runtime and the memory is allocated in bytes. The new operator denotes a request for dynamic memory allocation on the Heap. If sufficient memory is available then the new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
datatype *pointer_name = new datatype
int *ptr = new int; //We can declare a variable while dynamical allocation in the following two ways. int *ptr = new int (10); int *ptr = new int {15}; // new operator is also used to allocate a block(an array) of memory of type data-type. int *ptr = new int[20]; // The above statement dynamically allocates memory for 20 integers continuously of type int and returns a pointer to the first element of the sequence to ‘ptr’ pointer.
Note: If the heap does not have enough memory to allocate, the new request indicates failure by throwing an exception std::bad_alloc, unless “nothrow” is used with the new operator, in which case it returns a NULL pointer. Therefore, it is a good practice to check for the pointer variable produced by new before using it in the program.
Moving on with this article on Dynamic Memory Allocation in C++
Once heap memory is allocated to a variable or class object using the new keyword, we can deallocate that memory space using the delete keyword.
Syntax:
delete pointer_variable; // Here, pointer_variable is the pointer that points to the data object created by new. delete[] pointer_variable; //To free the dynamically allocated array memory pointed by pointer-variable we use the following form of delete:
Example:
delete ptr; delete[] ptr;
Note: The object’s extent or the object’s lifetime is the time for which the object remains in the memory during the program execution. Heap Memory allocation is slower than a stack, since, in heap, there is no particular order in which you can allocate memory whereas in the stack it follows LIFO.
Moving on with this article on Dynamic Memory Allocation in C++
The major use of the concept of dynamic memory allocation is for allocating memory to an array when we have to declare it by specifying its size but are not sure about it.
Let’s see, an example to understand its usage.
#include <iostream> using namespace std; int main() { int len, sum = 0; cout << "Enter the no. of students in the class" << endl; cin >> len; int *marks = new int[len]; //Dynamic memory allocation cout << "Enter the marks of each student" << endl; for( int i = 0; i < len; i++ ) { cin >> *(marks+i); } for( int i = 0; i < len; i++ ) { sum += *(marks+i); } cout << "sum is " << sum << endl; return 0; }
Explanation:
In this example first we ask the user for the number of students in a class and we store its value in the len variable. Then we declare an array of integer and allocate it space in memory dynamically equal to the value stored in the len variable using this statement int *marks = new int[length]; thus it is allocated a space equal to ‘length * (size of 1 integer)’. The rest of the code is self-explanatory.
Moving on with this article on Dynamic Memory Allocation in C++
We can also dynamically allocate objects.
As we know that Constructor a special class member function used to initialize an object and Destructor is also a class member function which is called whenever the object goes out of scope.
Destructor is can be used to release the memory assigned to the object. It is called in the following conditions.
We can again use pointers while dynamically allocating memory to objects.
Let’s see an example of an array of objects.
#include <iostream> using namespace std; class Random { public: Random() { cout << "Constructor" << endl; } ~Random() { cout << "Destructor" << endl; } }; int main() { Random* a = new Random[3]; delete [] a; // Delete array return 0; }
Output:
Explanation:
The Constructor will be called three times since we are allocating memory to three objects of the class Random. The Destructor will also be called three times during each of these objects. ‘Random* a = new Random[3];’ this statement is responsible for dynamic memory allocation of our object.
Thus we have come to an end of this article on ‘Dynamic Memory Allocation C++’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.
edureka.co