0

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?

jorgen
  • 2,791
  • 3
  • 25
  • 39
  • 7
    Windows won't necessarily free your program's memory back to the system itself - and so task manager won't tell you the whole truth. You certainly can't use it to detect/monitor memory leaks like this. – noelicus Nov 19 '13 at 12:35
  • There's no memory leak in this code (assuming the mpfr_* routines don't leak). A memory leak is when your program has less memory to use, if all that is happening is that less memory is available to the *system* then that isn't a memory leak. – john Nov 19 '13 at 12:40
  • @noelicus Oh I see.. Is there another way to check the memory usage without using an IDE on windows? I'm using cygwin but it seems the command 'top' is not available. john: Oh I guess I used the wrong name then – jorgen Nov 19 '13 at 12:43

1 Answers1

1

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.

Community
  • 1
  • 1
noelicus
  • 12,864
  • 2
  • 82
  • 94