LucasS
LucasS

Reputation: 729

Freeing Memory From An Array

I am experimenting with memory allocation and deletion and had a question about how to properly delete/free memory. Below is a very small and working bit of code:

#include <windows.h>
#include <vector>
#include <iostream>

using namespace std;

int main() {
    cout << "Initial" << endl;
    system("Pause");

    double* Array = new double[50000];
    for(int i = 0; i < 50000; i++)
    {
        Array[i] = rand();
    }

    cout << "Array created" << endl;
    system("Pause");

    delete[] Array;

    cout << "Array deleted" << endl;
    system("Pause");

    return 1;
}

During each system pause, I used Windows Task Manager to check how much memory my application was using. Below are the numbers from my results:

So have I missed something in my C++ education? Should the memory allocated for the array not be freed after delete[] is called?

Upvotes: 1

Views: 594

Answers (2)

Steel
Steel

Reputation: 125

It depends on compiler you use. For some compiler, memory deleted is hold by application, not returning to OS immediately. Sorry that I cannot find an official link about it now.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

No, you did not miss anything. It is just that the Task Manager is not telling you the whole truth (well, it does not tell you the truth from the perspective that you need). When you program calls delete[], the memory is released for reuse by the program, but it is not returned back to the operating system. From your program's point of view, the memory is freed: your next call of new will claim the same memory chunk. But from the OS's (and Task Manager's) point of view, the program still holds on to the memory.

To see what's going on, run your allocations several times, and deallocations in a loop, and see that the total amount of memory in the Task Manager does not go up from the "high water mark" that you get after the first allocation.

Upvotes: 4

Related Questions