In C++, dynamic memory allocation is the process of allocating memory at runtime using the new
operator. The new
operator returns a pointer to the allocated memory.
Example of dynamic memory allocation:
// Allocate an integer
int* ptr = new int;
// Allocate an array of 5 integers
int* arr = new int[5];
Dynamic memory allocation is useful in several scenarios:
After dynamically allocating memory, it's important to deallocate it using the delete
operator to avoid memory leaks.
Example of deallocating dynamically allocated memory:
// Deallocate the single integer
delete ptr;
// Deallocate the array of integers
delete[] arr;
It's also recommended to use smart pointers (e.g., unique_ptr
, shared_ptr
) that automatically handle memory deallocation.
Example of using a smart pointer for dynamic memory:
#include <memory>
// Allocate an integer
auto ptr = std::make_unique<int>(5);
// Allocate an array of 5 integers
auto arr = std::make_unique<int[]>(5);
By understanding dynamic memory allocation, you can create more flexible and efficient C++ programs that can handle varying amounts of data.
Answers to questions are automatically generated and may not have been reviewed.
Learn about stack allocation, limitations, and transitioning to the Free Store