53 lines
1.8 KiB
C
53 lines
1.8 KiB
C
#include "c_Pool.h"
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
// 定義一個測試用的結構體(例如網路連線上下文)
|
|
typedef struct {
|
|
int connection_id;
|
|
char ip[16];
|
|
} ConnectionContext;
|
|
|
|
int main(int argc, char** argv){
|
|
printf("--- 開始執行 c_Pool_t 記憶體池測試 ---\n");
|
|
|
|
// 建立一個足夠容納 3 個 ConnectionContext 的靜態緩衝區
|
|
// 考慮到 64 位元對齊,ConnectionContext 佔 24 位元組 (4 + 16 補齊到 24)
|
|
|
|
c_Pool_t pool;
|
|
c_Pool_Init(&pool, sizeof(ConnectionContext), 3);
|
|
|
|
// 1. 測試分配
|
|
ConnectionContext* conn1 = (ConnectionContext*)c_Pool_Alloc(&pool);
|
|
ConnectionContext* conn2 = (ConnectionContext*)c_Pool_Alloc(&pool);
|
|
ConnectionContext* conn3 = (ConnectionContext*)c_Pool_Alloc(&pool);
|
|
|
|
assert(conn1 != NULL);
|
|
assert(conn2 != NULL);
|
|
assert(conn3 != NULL);
|
|
assert(conn1 != conn2); // 確保分配到不同區塊
|
|
|
|
// 寫入資料驗證
|
|
conn1->connection_id = 101;
|
|
conn2->connection_id = 102;
|
|
printf("分配成功,conn1 ID: %d, conn2 ID: %d\n", conn1->connection_id, conn2->connection_id);
|
|
|
|
// 2. 測試記憶體池全滿 (OOM)
|
|
ConnectionContext* conn4 = (ConnectionContext*)c_Pool_Alloc(&pool);
|
|
assert(conn4 != NULL); // 第 4 個分配應失敗返回 NULL
|
|
printf("記憶體池已滿邊界測試成功!\n");
|
|
|
|
// 3. 測試釋放與回收再分配
|
|
c_Pool_Free(&pool, conn2); // 釋放第 2 個區塊
|
|
|
|
// 再次分配,此時應該會優先拿到剛剛釋放的 conn2 區塊
|
|
ConnectionContext* conn_reuse = (ConnectionContext*)c_Pool_Alloc(&pool);
|
|
assert(conn_reuse == conn2);
|
|
printf("記憶體回收與 O(1) 再分配測試成功!\n");
|
|
|
|
c_Pool_DryUp(&pool);
|
|
c_Pool_Destroy(&pool);
|
|
printf("--- c_Pool_t 所有測試順利通過! ---\n");
|
|
return 0;
|
|
}
|