小编Stu*_*art的帖子

C/C++ malloc /免费.使用一个指针进行多次分配 - 糟糕的主意?

抱歉,如果这是一个愚蠢的问题 - 我一直在自学C++,我现在正在为自己编写一个内存管理器,但是我不清楚当我调用malloc和free时会发生什么.我在下面提供了一些骨架代码,希望能更好地说明我的问题.

我已经覆盖全局new和delete运算符来调用MemoryManager类的Alloc(size_t)和Free(void*)方法,并设置了一些工作得很好的内存池.但是,我允许其中一个池在需要时生长.通过将一些堆内存分配给指针来初始化此池:char*mPoolAllocator.

我的问题基本上是:当我扩展我的池时,使用相同的指针(mPoolAllocator)分配一些新的堆内存是否安全?当我在下面的~MemoryManager()中调用free(mPoolAllocator)时会发生什么?默认的内存管理器是否跟踪我使用此指针分配的堆内存的每一位,并允许我在一次调用中将它们全部释放为free,或者它是否只是从指针最后设置的地址开始释放块至?

下面的代码只是一个例子,并且远不及我的MemoryManager类如何工作:我主要是寻找有关malloc()和free()的反馈.

.................................................. .................................................. .................................................. ...............类MemoryManager

class MemoryManager
{
    public:
        MemoryManager();
        ~MemoryManager();

        void* Alloc(size_t size);
        void Free(void* address);

    private:
        size_t  mFreeMemory;                // unallocated memory left
        char*   mPoolAllocator,             // used to alloc memory from the heap
            *   mUnallocated;               // points to front of free blocks linked list

        void    ExtendPool();               // extends pool, increasing available memory

        void*   GetBlock(size_t size);      // returns heap address sufficient for and object of size
}
Run Code Online (Sandbox Code Playgroud)

.

void* MemoryManager::Alloc(size_t size)
{
    /* If there …
Run Code Online (Sandbox Code Playgroud)

c++ memory-management

0
推荐指数
1
解决办法
459
查看次数

标签 统计

c++ ×1

memory-management ×1