删除有时不释放内存

时间:2017-03-07 05:59:11

标签: c++ heap-memory delete-operator

http://www.cplusplus.com/reference/new/operator%20delete[]/

我的代码段

...
{
    MyClass * pt;
    pt = new MyClass[10000];
    delete [] pt;
    pt = NULL;
}
{
    MyClass * pt;
    pt = new MyClass[10000];
    delete [] pt;
    pt = NULL;
}
...

两次做同样的事情

我通过htop监控了流程RES。

我发现第一次删除DO空闲内存,但第二次删除不释放内存。

为什么?

===更新

struct MyClass
{
    static int counter;
    MyClass() {
        counter++;
    }
    ~MyClass() {
        counter--;
    }
    ...
    ...
};


int MyClass::counter = 0;

...
{
    MyClass * pt;
    pt = new MyClass[10000];
    printf("delete-1  %x %d", pt, pt->counter);
    delete [] pt;
    pt = NULL;
    printf("delete-1  %x %d", pt, pt->counter);
}
{
    MyClass * pt;
    pt = new MyClass[10000];
    printf("delete-2  %x %d", pt, pt->counter);
    delete [] pt;
    pt = NULL;
    printf("delete-2  %x %d", pt, pt->counter);
}
...

输出:

delete-1 6c3c6018 10000

delete-1 0 0

delete-2 54000aa8 10000

delete-2 0 0

再次实施(不要杀死进程)

delete-1 4c900958 10000

delete-1 0 0

delete-2 4c900958 10000(这个新的不要增加RES)

delete-2 0 0

结果:

记忆力不断增强:'(

只有第一个删除DO空闲内存

0 个答案:

没有答案