The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

How to Safely Use new[] and delete[] in C++

In C++, new[] and delete[] are used for dynamic memory allocation and deallocation for arrays. Unlike new and delete which are used for single objects, new[] and delete[] are specifically designed for arrays of objects. However, it’s important to use them properly to avoid memory leaks, undefined behavior, and other issues.

1. Using new[] for Dynamic Array Allocation

new[] allocates memory for an array of objects. The syntax looks like this:

cpp
int* arr = new int[10];

In this case, an array of 10 integers is dynamically allocated. The type of the array (int in this case) can be any data type, and you can allocate arrays of any size.

Key Points:

  • The number of elements in the array must be known at runtime. You cannot use new[] to allocate a statically sized array.

  • new[] returns a pointer to the first element of the array.

  • The memory is allocated on the heap, and thus needs to be manually freed when it is no longer needed.

2. Using delete[] for Array Deallocation

delete[] is used to deallocate the memory that was allocated by new[]. The syntax is:

cpp
delete[] arr;

This deallocates the memory that was dynamically allocated for the array, releasing the space back to the heap.

Key Points:

  • You must use delete[] and not delete for arrays allocated with new[]. Using delete on an array allocated with new[] leads to undefined behavior because the array will not be properly deallocated.

  • After deallocating memory, the pointer (arr in this case) becomes a dangling pointer. It’s a good practice to set it to nullptr after deletion to avoid accessing freed memory.

Example Code for Correct Use:

cpp
#include <iostream> int main() { // Dynamically allocate an array of 10 integers int* arr = new int[10]; // Initialize array elements for (int i = 0; i < 10; ++i) { arr[i] = i * 10; } // Print array elements for (int i = 0; i < 10; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; // Deallocate the array memory delete[] arr; arr = nullptr; // Prevent dangling pointer return 0; }

3. Common Pitfalls with new[] and delete[]

A. Memory Leaks

Memory leaks happen if you forget to deallocate memory using delete[]. This can lead to wasted memory, especially in long-running applications or those allocating many arrays. Always ensure that every new[] has a matching delete[].

B. Using delete Instead of delete[]

If you mistakenly use delete instead of delete[], the compiler may not know how to properly deallocate the array. This can lead to undefined behavior or partial memory deallocation. Always use delete[] for arrays allocated with new[].

C. Dangling Pointers

After deallocating memory with delete[], the pointer used to point to the array still holds the memory address. If you attempt to access or modify this memory, it results in undefined behavior. Setting the pointer to nullptr after deletion ensures you don’t mistakenly use the dangling pointer.

D. Double Deletion

You should never call delete[] on the same pointer more than once. Once the memory has been freed, the pointer becomes invalid, and any subsequent attempt to free it again will lead to undefined behavior.

cpp
delete[] arr; // valid delete[] arr; // undefined behavior

4. Best Practices for Using new[] and delete[]

A. Avoid Raw Pointers When Possible

While new[] and delete[] work fine, modern C++ (since C++11) encourages the use of smart pointers like std::unique_ptr and std::shared_ptr, as well as containers like std::vector. These abstractions automate memory management, reducing the risk of memory leaks and dangling pointers.

B. Use RAII Principle

RAII (Resource Acquisition Is Initialization) is a core concept in C++ where resources (like memory) are acquired during object initialization and released during object destruction. Using smart pointers or containers like std::vector automatically handles memory management, so you don’t need to worry about manually calling delete[].

Example using std::vector:

cpp
#include <vector> #include <iostream> int main() { // Use a vector for dynamic arrays instead of new[] std::vector<int> arr(10); // Initialize array elements for (int i = 0; i < 10; ++i) { arr[i] = i * 10; } // Print array elements for (int i = 0; i < 10; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; // No need to manually delete memory, vector handles it return 0; }

C. Prefer std::vector Over new[]

For dynamic arrays, std::vector is generally a better alternative than new[] and delete[]. It handles memory management automatically and provides useful member functions (like resizing) that make it more flexible and safer to use.

5. Conclusion

When using new[] and delete[] in C++, always ensure that:

  1. You use new[] to allocate arrays and delete[] to deallocate them.

  2. Avoid mixing new[] and delete.

  3. Set the pointer to nullptr after deallocation to prevent dangling pointers.

  4. Prefer smart pointers or standard containers like std::vector whenever possible to automate memory management and avoid errors.

By following these guidelines, you can safely use dynamic memory allocation in C++ without encountering the common pitfalls.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About