user2833876 user2833876 - 1 year ago 138
C++ Question

Deallocate dynamic memory

I have written some code like this:

double *psi1 = multiplyscalar(
multiplyscalar(submatrix( multiplyscalar(I3, ttt2, 3, 3), multiplyscalar(multiply(teta0, teta0t, 3, 1, 1, 3), pow(*ttt, -1.5), 3, 3),3,3), 2, 3, 3)
,( (*multiply(A3t, mu, 1, m, m, 1))-( *multiply(multiply(multiply(transpose(mu, m, 1), G1, 1, m, m, m),transpose(G, m, m), 1, m, m, m), mu, 1,m,m,1) ) )

Where the functions called are similar to this:

static double* multiply(double A[], double B[], int ra, int ca, int rb, int cb){
if(ca != rb){
hal.console->printf("\n multiplication error\n");
return nullptr;
double* C = new double[ra*cb];
double sum = 0;
for(int i = 0; i < ra; ++i){
for(int j=0; j<cb; j++){
for(int x=0; x<ca; x++){
sum += A[(i*ca)+x]*B[(x*cb)+j];
C[(i*cb)+j] = sum;
sum = 0;
return C;}

So I have memory leak because those pointers that are returned are never "erased".

Is there a way to
them afterward?
I know doing every operation separately would bypass the issue, but I was searching for a more elegant solution?

Answer Source

Return a proper container, e.g. some std::vector (or your class using it). Read also about the rule of five.

Maybe define a template function (with the template arguments being the sizes, perhaps using std::array).

Consider also smart pointers (like std::unique_ptr), avoiding explicit new and delete.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download