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

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

问题描述

我跟内存分配和删除实验和有一个关于如何正确删除/空闲内存的问题。下面是code的一个非常小的和工作位:

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 ++教育的东西吗?如果内存分配给数组不会被释放后删除[]被称为?

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

推荐答案

没有,你没有错过任何东西。它只是任务管理器是不会告诉你全部真相(当然,它不会告诉你,你需要的角度真相)。当你的程序调用删除[] ,内存被释放供程序重用,但它不返回到操作系统。但从程序的角度来看,内存被释放:你的下一个电话将声称相同的内存块。但是从操作系统(以及任务管理器的)来看,该方案仍持有到内存中。

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天全站免登陆