sky6502 2014-12-13 12:49 采纳率: 100%
浏览 2367
已采纳

C++内存泄露,只是动态申请对象,然后delete就发生了内存泄露,真奇怪。

今天写了个样例程序,程序主要是动态创建一个类的对象,存入list链表中,然后再把链表中的对象delete掉回收内存,理论上并不应该会产生内存泄露,但是从现象上来看确实是发生了内存泄露。程序启动后我分别在“创建对象前”、“创建对象后”、“释放对象内存后”三个阶段使用命令ps -aux|grep a.out查看了程序使用内存情况,发现在“释放对象内存后”阶段并没有释放对象的资源,回收内存。

使用命令查看程序使用内存情况如下:

[root@test2 ~]# ps -aux|grep a.out

Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ

root 37559 0.0 0.0 11752 960 pts/0 S+ 20:21 0:00 ./a.out

root 37561 0.0 0.0 105308 868 pts/2 S+ 20:21 0:00 grep a.out

[root@test2 ~]# ps -aux|grep a.out

Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ

root 37559 6.0 0.4 324328 313496 pts/0 S+ 20:21 0:00 ./a.out

root 37563 0.0 0.0 105308 872 pts/2 S+ 20:21 0:00 grep a.out

[root@test2 ~]# ps -aux|grep a.out

Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ

root 37559 4.6 0.4 324328 313540 pts/0 S+ 20:21 0:00 ./a.out

root 37565 0.0 0.0 105308 872 pts/2 S+ 20:21 0:00 grep a.out

[root@test2 ~]# ps -aux|grep a.out

Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ

root 37559 3.2 0.4 324328 313540 pts/0 S+ 20:21 0:00 ./a.out

root 37567 0.0 0.0 105308 868 pts/2 S+ 20:21 0:00 grep a.out

程序如下:

    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <list>
    using namespace std;

    class basicClass
    {
    public:
            basicClass()
        {
            a = 0; 
            b = 0;
            c = 0;
        }
        virtual ~basicClass()
        {
    //      cout<<"basic class release\n";
        }
    public:
        virtual int print()
        {
            cout<<"a:"<<a<<endl;
            return 0;
        }
    protected:
        int a;
        int b;
        int c;
        int arr;
    };

    int main(void)
    {
        printf("init stat\n");
        getchar();
        list<basicClass*> classList;
        for (int i = 0; i < 5000000; i++)
        {
            basicClass *pClass = new basicClass();
            classList.push_back(pClass);
        }

        printf("insert finish\n");
        getchar();
        unsigned int i = 0;
        for (list<basicClass*>::iterator iter = classList.begin(); iter != classList.end(); iter++)
        {
            i++;
            delete *iter;
        }
        classList.clear();
        printf("release finish\n");
        printf("release count:%d\n", i);
        getchar();

            return 0;
    }

  • 写回答

6条回答 默认 最新

  • sky6502 2014-12-15 11:17
    关注

    已解决,在delete所有对象后调用mallo__trim(0)就好了。_

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频