naglas
naglas

Reputation: 492

How to properly deallocate memory for a 2d array in C++?

Here's how I allocate it:

float** matrix = new float*[size];
for (int i = 0; i < size; i++) {
    matrix[i] = new float[size];
}

And here's how I deallocate:

if (matrix != nullptr) {
    for (int i = 0; i < size; i++) {
        delete[] matrix[i];
    }
}
free(matrix);

Is this correct or should I also delete[] the outer array?

Upvotes: 1

Views: 1304

Answers (2)

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

How to properly deallocate memory for a 2d array in C++?

Not manually. Use an abstraction like std::vector that deallocates memory for you thanks to RAII, or std::array if you know the size of your matrix at compile-time.

{
    std::vector<std::vector<float>> matrix(size);
    for(auto& v : matrix) v.resize(size);
}

// memory automatically freed at the end of the scope

You should almost never use new and delete in Modern C++. Refer to my answer here for more information: Malloc vs New for Primitives


If you are writing a program that requires an high-performance matrix implementation, please do not create your own. Your code and my example using std::vector both have a cache-unfriendly jagged layout which can severely harm performance. Consider using an high-quality production-ready library such as Eigen, Blaze, or BLAS instead.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234685

delete[] is always paired with a new[].

delete is always paired with a new.

So yes, in your case, you need to call delete[] matrix; to release the array of float* pointers. Don't use free unless that pointer has been obtained with a call to malloc &c., which would be unusual in C++.

Although, if you want to model a matrix in the mathematical sense then might I suggest you use a 3rd partly library. I use BLAS, part of the Boost distribution.

Upvotes: 4

Related Questions