How to allocate memory dynamically in C++
What is Memory Allocation?
“Memory allocation is the process of allocating and reserving space in a computer's memory for the storage of data while a programme is being run.” It enables the creation and management of variables and data structures by programmes. There are two primary types: heap allocation for dynamic data and automatic stack allocation for local variables. While heap allocation is more versatile but requires manual memory management to prevent memory leaks, stack allocation is quicker but has a smaller size limit.
What is Dynamic Memory Allocation in C++?
The technique of allocating memory for variables or data structures during runtime (during the execution of a programme) as opposed to at compile time is known as dynamic memory allocation in C++. It gives you additional freedom in how you manage memory resources by allowing you to construct variables whose size or lifetime are unknown at compile time.
The following operators are usually used in C++ when allocating dynamic memory:
1.new operator
new: The memory for a single object on the heap is dynamically allocated using the new operator. It gives back a pointer to the RAM that was allotted.
int* ptr = new int; // Allocates memory for a single integer
The accumulation has the potential to be used to dynamically allocate memory for an array of objects employing the percentage of the new[] operator. subsequently provides back an offset to the array's beginning component.
int* arr = new int[5]; // Allocates memory for an array of 5 integers
To prevent memory leaks, you must make sure to deallocate the memory allocated dynamically using new or new[ when it is no longer required. When you forget to free up the memory you've been allotted, you develop memory leaks, which eventually deplete RAM.
2.delete operator
Use the delete and delete[] operators, respectively, to deallocate dynamic memory:
delete ptr; // Deallocates memory for the single integer
delete[] arr; // Deallocates memory for the array of integers
Alternatively, in modern C++, you can use smart pointers (std::unique_ptr and std::shared_ptr) to handle memory deallocation automatically and safely.
#include <memory>
std::unique_ptr<int> ptr = std::make_unique<int>(); // Smart pointer for single
std::unique_ptr<int[]> arr = std::make_unique<int[]>(5); // Smart pointer for array of integers
When you need to create data structures of various sizes or you want to manage the lifetime of data after the current function or block, dynamic memory allocation can be helpful. To avoid memory leaks and unpredictable behaviour, however, exercise caution when employing dynamic memory.
Example 1
#include <iostream>
int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;
int* arr = new int[size];
std::cout << "Enter " << size << " integers:\n";
for (int i = 0; i < size; ++i) {
std::cin >> arr[i];
}
std::cout << "The values in the array are: ";
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
delete[] arr;
return 0;
}
Output
![How to allocate memory dynamically in C++](https://static.tutorialandexample.com/cpp/how-to-allocate-memory-dynamically-in-cpp1.png)
In this illustration, the programme first requests the size of an integer array from the user before dynamically allocating memory for the array based on the input from the user and requesting values for the array elements. The array's values are then shown, and the memory is deallocated using delete[] to free up space when it has served its purpose.
To avoid memory leaks and maintain effective memory management, keep in mind that dynamic memory allocation should only be used sparingly and that it is imperative to deallocate the memory using delete[]. For more reliable and secure memory management in contemporary C++, think about adopting smart pointers or industry-standard containers like std::vector.
Example 2
In C++, a single object is dynamically allocated by making an object on the heap rather than the stack. This enables you to manually control the object's production and destruction and gives it a dynamic lifetime. Here is an illustration of a single object's dynamic allocation:
#include <iostream>
class MyClass {
public:
MyClass(int value) : data(value) {
std::cout << "Constructor called with value: " << data << std::endl;
}
~MyClass() {
std::cout << "Destructor called for value: " << data << std::endl;
}
void printData() const {
std::cout << "Data: " << data << std::endl;
}
private:
int data;
};
int main() {
MyClass* objPtr = new MyClass(42);
objPtr->printData();
delete objPtr;
return 0;
}
Output
![How to allocate memory dynamically in C++](https://static.tutorialandexample.com/cpp/how-to-allocate-memory-dynamically-in-cpp2.png)
We develop a basic MyClass in this example, complete with a constructor and destructor. Using the new operator in the main function, we dynamically allocate a MyClass object on the heap. With the supplied value (in this case, 42), the constructor is called, and the object is created.
We explicitly deallocate the memory using the delete operator after utilising the object. The dynamically allocated memory is released after the destructor has been called. To avoid memory leaks, it's imperative to remember to deallocate dynamically allocated memory.
In addition, current C++ offers smart pointers (std::unique_ptr and std::shared_ptr) for safer and more automatic memory management, minimising the need for manual delete. Just keep in mind that dynamic allocation should be used sparingly.
Conclusion
You can build objects and data structures with a configurable lifetime on the heap by using dynamic memory allocation in C++. 'new' and 'delete' commands must be used manually to control memory. Take care to prevent memory leaks and unpredictable behaviour. For safer memory management, think about employing smart pointers. When you require data of various sizes or objects with complicated lives, use dynamic allocation. To guarantee the effectiveness and stability of the programme, responsible use is crucial.adaptable but well-organized code, despite certain possible drawbacks.