Dynamic memory allocation in C++ allows the program to allocate memory during runtime, which is especially useful when the size of the data structure isn’t known in advance. Using new
and delete
, we can manage memory manually, creating and releasing memory on the heap as needed. Let’s break down how dynamic memory allocation works, memory management basics, and the concept of pointers to pointers.
Dynamic Memory Allocation with new
and delete
In C++, new
is used to allocate memory on the heap, and delete
is used to release that memory. This is essential for managing resources effectively, especially when creating objects or arrays whose sizes can vary at runtime.
new
Operator: Allocates memory on the heap and returns a pointer to it.delete
Operator: Frees the memory previously allocated bynew
.
Example: Allocating and deleting a single integer dynamically.
In this example:
- We allocate memory for an integer using
new int
and store the address inptr
. - We assign a value to
*ptr
, which is the memory pointed to byptr
. - We then release the memory with
delete ptr
and setptr
tonullptr
to avoid accidental use.
Dynamic Arrays with new
and delete[]
When working with arrays whose size is determined at runtime, new
allows us to allocate arrays dynamically. We use delete[]
to release the entire array from memory.
Example: Allocating and deleting a dynamic array.
Here:
- We allocate an array of integers with a size defined by user input.
- We release the memory with
delete[] arr
to free the entire array.
Memory Management Best Practices
Proper memory management is crucial in C++ to avoid issues like memory leaks and dangling pointers:
- Always release memory: Use
delete
ordelete[]
after you’re done with dynamically allocated memory. - Avoid multiple deletions: Deleting the same pointer twice can cause undefined behavior.
- Nullify pointers after deletion: Setting a pointer to
nullptr
after deletion helps prevent accidental access to freed memory.
In this example:
ptr
holds the address ofvalue
.ptrToPtr
holds the address ofptr
.**ptrToPtr
gives us the original value by dereferencing twice.
Dynamic Multi-Dimensional Arrays with Pointers to Pointers
Using pointers to pointers, we can create dynamic multi-dimensional arrays. This is useful when the number of rows and columns may vary at runtime.
Example: Creating a dynamic 2D array.
In this example:
- We first allocate memory for rows as an array of
int*
. - For each row, we allocate memory for
cols
elements, effectively creating a 2D array. - We release memory row by row and then delete the row pointers to avoid memory leaks.