-2

This program creates 5,000,000 objects and pushes the objects into a list. It then deletes the objects and the program suffers a memory leak. I have found some information about glibc. It says glibc can cause memory fragmentation, so I used tcmalloc instead, but it also can not Recovery of memory.

#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;
}
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79

1 Answers1

1

Many libraries create memory pools. That is, they allocate some memory to satisfy your request, then when you free your memory, they don't free their own memory. If done right that enables them to satisfy your second and subsequent requests much quicker.

Or ae you saying that the Resident Set Size of your process continued to increase? That's the number of pages that are physically resident in memory. In general your virtual memory will be equal to or greater than the Resident Set Size.

Some memory allocators work by placing "bookkeeping" data structures between your allocations, typically in a linked list. When you delete a block, your allocator reads from that writes into the bookkeeping structure for that particular block. That will lead to a paged-out memory block becoming resident.

In that case it's a problem for the kernel and your development system, not really something you can do much about.

Mike Crawford
  • 2,232
  • 2
  • 18
  • 28
  • The physical memory continued reduce,finally the memory maybe use up.How to solve the program? – developLearner Dec 14 '14 at 11:39
  • Are you saying that the Resident Set Size of your process continued to increase? That's the number of pages that are physically resident in memory. In general your virtual memory will be equal to or greater than the Resident Set Size. – Mike Crawford Dec 14 '14 at 12:55