jorgen
jorgen

Reputation: 3593

Memory leak with dynamic array of mpfr variables in c++

I have a simple c++ program using the multiprecision library MPFR written to try and understand a memory problem in a bigger program:

int main() {

  int prec=65536, size=1, newsize=1;
  mpfr_t **mf;

  while(true) {

    size=newsize;
    mf=new mpfr_t*[size];
    for(int i=0;i<size;i++) {
        mf[i]=new mpfr_t[size];
        for(int j=0;j<size;j++) mpfr_init2(mf[i][j], prec);
    }

    cout << "Size of array: ";
    cin >> newsize;

    for(int i=0;i<size;i++) {
        for(int j=0;j<size;j++) mpfr_clear(mf[i][j]);
        delete [] mf[i];
    }
    delete [] mf;
  }
}

The point here is to declare arrays of different sizes and monitor the memory usage with task manager (I'm using Windows). This works fine for sizes ~< 200 but if I declare something larger the memory doesn't seem to be freed up when I decrease the size again.

Here's an example run: I start the program and choose size 50. Then I change sizes between 50, 100, 150 and 200 and see the memory usage go up and down as expected. I then choose size 250 and the memory usage goes up as expected but when I go back to 200 it doesn't decrease but increases to something like the sum of the memory values needed for size 200 and 250 respectively. A similar behaviour is seen with bigger sizes.

Any idea what's going on?

Upvotes: 0

Views: 363

Answers (1)

noelicus
noelicus

Reputation: 15055

Process Explorer will give you a more realistic view of your process's memory usage (Virtual Size) than Task Manager will. A memory leak is when a program doesn't free memory is should and if this happens all the time it's memory will never stop increasing.

Windows won't necessarily free your program's memory back to the system itself - and so task manager etc won't tell you the whole truth.

To detect memory leaks in visual studio you can enable the _CRTDBG_MAP_ALLOC macro, as described on this MSDN page.

Also this question talks a bit about making it work with C++ new keyword.

Upvotes: 1

Related Questions