一个简单的内存管理器

#include <iostream>
using namespace std;
/*
 * 内存管理器,分配大块内存供使用,最后集中回收
 */
class AllocMem {
private:
    enum {BlockSize = 2048};//buffer尺寸大小
    struct Block {
        Block *next;
        char buffer[BlockSize];
    };//分配内存的基本单元

    Block *pHead;
    enum {HeaderSize = sizeof(Block) - BlockSize};
    char *m_begin;//指向空闲内存开始的地址
    char *m_end;//指向空闲内存结束的地址

public:
    AllocMem();
    ~AllocMem();
    void *alloc(int n);
    
private:
    void clear(); // 析构并释放所有分配的对象
};


AllocMem::AllocMem(){
    m_begin = m_end = nullptr;
    pHead = nullptr;
}
AllocMem::~AllocMem(){
    clear();
}
void *AllocMem::alloc(int n) {
    int size = m_end - m_begin;//m_end > m_begin,地址增长方向

    if (size < n) {
        if (n > BlockSize) {
            Block *p = (Block *) malloc(n + HeaderSize);
            if (pHead){
                p->next = pHead->next;
                pHead->next = p;
            } else{
                m_end = m_begin = p->buffer;
                pHead = p;
                p->next = nullptr;
            }
            return p->buffer;
        }
        else {
            Block *p = (Block*)malloc(sizeof(Block));
            p->next = pHead;
            m_begin = p->buffer;
            m_end = m_begin + BlockSize;
        }
    }
    return m_end = m_end - n;
}
void AllocMem::clear(){
    Block *p = pHead;
    Block *q = nullptr;
    while (p){
        q = p->next;
        delete p;
        p = q;
    }
    m_end = m_begin = nullptr;
}


int main(){
    AllocMem alloc;
    double *a = (double *)alloc.alloc(sizeof(double));
    *a = 4.5;
    double *b = (double*) alloc.alloc(sizeof(double));
    cout << *a  << " " << b << endl;
}

 

posted @ 2020-06-03 19:36  hello.world!  阅读(304)  评论(0编辑  收藏  举报