I'm still learning C ++ and have a question that might be obvious, or maybe I just don't know what I'm trying to do. I have functions that take a matrix (the class I wrote that has a correctly written destructor) and create a new matrix from it, returning a link to the new one. I need iterations, perhaps tens of thousands of times on these matrices, so I need to make sure that I have no memory leaks. So the question is, how to remove the matrix that I no longer need to make space for the next? Here is the code I'm trying to get without leaks:
DynamicMatrix<double> x0 = getX0(n); DynamicMatrix<double>exactU = getExactU(n); DynamicMatrix<double> b = getB(n) * w; DynamicMatrix<double> x1 = getX1(x0, b, w, n); while( !isConverged(exactU,x1,e) ){ delete x0;
Each of the getX () methods creates a pointer to the matrix and returns a reference to the matrix, as in getX0 ():
DynamicMatrix<double> &getX0(int n){ DynamicMatrix<double>* mat1 = new DynamicMatrix<double>(n * n,1); for (int i = 1 ; i <= n; i++){ for (int j = 1; j <= n; j++){ mat1->set((i-1)*n +j, 1, 0); } } return *mat1; }
So, the call is "delete X0" because it needs a pointer. 'delete & X0' says that the freed pointer was not highlighted. What is the right way to do this? Or am I doing something completely wrong? With matrices too large and with too many iterations, my large hard drive runs out of space, which I can only assume that I have a memory leak in abundance.
source share