0

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.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
saeed
  • 1

1 Answers1

6

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)
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • how can i use std::vector or RAII? can you explain more? – saeed Aug 17 '13 at 06:52
  • 2
    @saeed look at the beginner end reference section in [this list of books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – juanchopanza Aug 17 '13 at 06:55