代理向量的指针,但内存仍在使用中 [英] Deallocating vector of pointers, but memory still in use

查看:112
本文介绍了代理向量的指针,但内存仍在使用中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道以下代码有什么问题!我删除所有指针,但是当我使用top命令来观看内存,我可以看到仍然有大量的内存分配给程序。我缺少这里的东西来释放内存吗?

I have no idea what's wrong with the following code! I am deleting all pointers, but when I use the "top" command to watch the memory, I can see that still lots of memory is allocated to the program. Am I missing something here to free the memory?

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int*> container;
    vector<int*>::iterator itr;
    unsigned long long i;

    for(i = 0; i < 10000000; i++)
    {
        int* temp = new int();
        *temp = 1;
        container.push_back(temp);
    }

    for(itr = container.begin(); itr != container.end(); itr++)
    {
        delete *itr;
        *itr = NULL;
    }

    container.clear();
    cout<<"\nafter clear\n";

    while(1)
    {
        sleep(1000000);
    }

    return 0;
}


推荐答案

代码(假设在所有交换之后和释放之前没有抛出异常)。你没有看到内存下降的原因是CRT可能不会释放你删除的内存立即返回到进程。它可能会保留以备将来使用。但是,保证一旦进程终止,内存将被释放。

There is no leak in this code (Assuming there are no exceptions being thrown after allcoation and before deallocation). The reason why that you are not seeing memory coming down is that the CRT may not release the memory you delete immediately back to the process. It might keep it for future use. However, it is guaranteed that the memory will be released once the process terminates.

这篇关于代理向量的指针,但内存仍在使用中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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