如果这是一个愚蠢的问题,我会道歉 - 我一直在自学C,目前正在为自己编写一个记忆管理员,但我不清楚当我调用malloc并且免费时会发生什么 . 我在下面提供了一些骨架代码,希望能更好地说明我的问题 .
我已经覆盖全局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
}
.
void* MemoryManager::Alloc(size_t size)
{
/* If there is free memory */
if(size <= mFreeMemory)
{
return GetBlock(size);
}
else // else create new free memory
{
ExtendPool();
return GetBlock(size);
}
}
.
void MemoryManager::ExtendPool()
{
mPoolAllocator = (char*)malloc(POOL_EXTEND_SIZE);
// some calls to functions that split the extended pool into blocks
mUnallocated = mPoolAllocator; // point to the next unallocated memory block (beginning of extended pool)
}
.
MemoryManager::~MemoryManager()
{
free(mPoolAllocator);
}
1 回答
不,那会泄漏内存 .
来自
malloc()
的每个返回值必须用作对free()
的不同调用中的参数 . 对于这种用法,请查看realloc()
,它将使其更像您期望的工作,因为它允许您增长已经分配的堆内存 .从
malloc()
返回的前一个指针的mPoolAllocator
变量中没有跟踪 .另外,在C中,你不应该使用
new[]
来分配字节数组吗?