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.