从数组中释放内存 [英] Freeing Memory From An Array

查看:37
本文介绍了从数组中释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验内存分配和删除,并有一个关于如何正确删除/释放内存的问题.下面是一小段非常有效的代码:

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;
}

在每次系统暂停期间,我使用 Windows 任务管理器检查我的应用程序使用了多少内存.以下是我的结果中的数字:

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:

  • 初始 744 KB
  • 创建的数组 1120 KB
  • 阵列已删除 1124 KB

那么我在 C++ 教育中错过了什么吗?调用delete[]后不应该释放为数组分配的内存吗?

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

推荐答案

不,您没有错过任何东西.只是任务管理器没有告诉您全部真相(好吧,它没有从您需要的角度告诉您真相).当您程序调用delete[] 时,内存会被释放以供程序重用,但不会返回给操作系统.从您的程序的角度来看,内存被释放:您下一次调用 new 将要求相同的内存块.但从操作系统(和任务管理器)的角度来看,程序仍然保留在内存中.

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.

这篇关于从数组中释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆