saeed
saeed

Reputation: 1

How can I avoid these kinds of memory leaks in my C++ code?

I have memory leak problem with my C++ code. I think this is because of pointer assignment. For example, I have several lines like this:

**int **p= new int *[g+2];          
for(int k=0;k<=g+1;k++){
    p[k]=new int [n_k[k]+1];
    for(int l=0;l<=n_k[k];l++){
        p[k][l]=0;
    }
}
int **temp= new int *[g+2];     
for(int k=0;k<=g+1;k++){
    temp[k]=new int [n_k[k]+1];
    for(int l=0;l<=n_k[k];l++){
        temp[k][l]=p[k][l];
    }
}
  ...
  ...
 for(int r=0; r<=g+1;r++){
delete []temp[r];
  }
  delete []temp;
  for(int r=0; r<=g+1;r++){
delete []p[r];
  }
   delete []p;

How can I avoid these kinds of memory leaks? I delete the pointers but I think the memory leaks are because of pointer assignments. I've used such pointer assignments several times in my code.

Upvotes: 0

Views: 129

Answers (1)

Alok Save
Alok Save

Reputation: 206508

How can I avoid these kinds of memory leaks in my C++ code?

  • Stop using new.
  • Avoid using dynamic memory allocations at all if you can.
    If you must:
  • use standard library containers like a std::vector or
  • use RAII(through smart pointers)

Upvotes: 6

Related Questions