Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c++ - 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:

  • Initial 744 KB
  • Array Created 1120 KB
  • Array Deleted 1124 KB

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...