Dynamic Memory Allocation
How do you dynamically allocate memory in C++, and why is it useful?
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:
- When the size of the data is not known at compile time (e.g., user input).
- When you need to allocate large amounts of memory that would exceed the stack size.
- When you need data to persist beyond the scope of a function.
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.
Memory Management and the Stack
Learn about stack allocation, limitations, and transitioning to the Free Store