標準庫 realloc 可直接擴充動態陣列;若需自行實作記憶體池,可參考下列概念:
int *pool = NULL;
int *poolPtr = NULL;
int poolSize = 0;
void *my_malloc(int bytes)
{
if (pool == NULL)
{
poolSize = 1024 * 1024; // 1 MB 初始池
pool = malloc(poolSize);
poolPtr = pool;
}
if ((char*)poolPtr + bytes - (char*)pool > poolSize)
return NULL; // 池耗盡
void *ret = poolPtr;
poolPtr = (int*)((char*)poolPtr + bytes);
return ret;
}
每次需求記憶體呼叫 my_malloc(sizeof(int) * 新元素數),回傳起始位址。此為極簡線性配置器,真實專案建議直接使用 realloc 或成熟記憶體池庫(如 jemalloc、tcmalloc)。