Fix memory leak in radTSend::OutRelaxResultsInfo#3
Fix memory leak in radTSend::OutRelaxResultsInfo#3per-gron wants to merge 1 commit intoochubar:masterfrom
Conversation
TotOutArray was not properly deallocated.
| double *t = TotOutArray; | ||
| std::vector<double> TotOutArray; | ||
| TotOutArray.resize(TotOutElem); | ||
| double *t = TotOutArray.data(); |
There was a problem hiding this comment.
Nice catch, and very good hint how to work with vector data via double* !
In this case, double* RelaxStatusParamArray can probably be directly submitted to MultiDimArrayOfDouble(..); I'll check this further and correct. Thanks!
There was a problem hiding this comment.
Glad to be of help.
If you want to give ownership of an object when calling a function, C++11 makes it possible to give objects like a vector to a function without expensive copying. For example:
void StoreMultiDimArrayOfDouble(std::vector<double> Array, int* Dims, int NumDims);
// And then call the function like this
StoreMultiDimArrayOfDouble(std::move(param), dims, n_dims);Compared to passing a raw pointer with the soft contract that the ownership is given to the function, with this approach there is no ambiguity and much lower risk of mistakes.
If you want to go a little deeper, effectively the same thing could be done, ever so slightly more efficiently, with
void StoreMultiDimArrayOfDouble(std::vector<double>&& Array, int* Dims, int NumDims);This is an "rvalue reference", a new kind of reference that is similar to a normal reference but it also means that the recipient of it is allowed to consume the object, the caller promises that the next method call is either the destructor or assignment operator. (std::move doesn't actually move, what it does is to return an rvalue reference to its parameter. Code that uses std::move should make sure to not use the moved object afterwards)
TotOutArraywas not properly deallocated. This PR changes the code to usestd::vector, which is a more idiomatic way to handle dynamically sized arrays, and it automatically manages the memory.If the memory allocation fails, an exception is thrown. (But: C++ code is almost always written with the assumption that memory allocations do not fail. It is very hard to write programs that use dynamic memory allocation and that work when memory allocations fail. It is more common to avoid dynamic memory allocation altogether if that is a concern.)
The
.resize()call will zero-initialize the vector, which carries a performance penalty. This performance penalty will be tiny if the vector is small enough to fit on a cache page aka 4K. If you worry about this, it is possible to useunique_ptrinstead ofvector.I found this with Address Sanitizer. The change removes the warning and seems to work. The change is tested on Linux/Clang only.