1. 首页
  2. 编程语言
  3. C++ 
  4. xmempool 内存池

xmempool 内存池

上传者: 2018-12-08 16:50:05上传 ZIP文件 14KB 热度 165次
C语言版简单内存池的实现。 X Memo Pool A memory pool implemented by C. Usage Create Pool At first you should create a pool handler for your data (or structure). xmem_pool_handler xmem_create_pool(unsigned int block_size); xmem_pool_hander is only a pointer which typedefed at xmempool.h. typedef void* xmem_pool_handler; For an example: typedef struct stct { int id; char str[16]; } stct; xmem_pool_handler pool1 = xmem_create_pool(sizeof(stct)); xmem_pool_handler pool2 = xmem_create_pool(sizeof(int)); if(!pool1 || !pool2) pr intf("Can't alloc more space\n"); Allocate Memory You can get a space of a certain size via function: void* xmem_alloc(xmem_pool_handle handle); For an example: stct* my_stct = xmem_alloc(pool1); if(!my_stct) printf("Can't alloc more space.\n"); And then you will get a whole empty space that fits stct. Recover Memory After your scope you want to recover your memory, don't use free(). There's a function below: int xmem_free(xmem_pool_handle handle, void* pointer); The return value: 0: invalid pool handler or the pointer not belongs to this pool, can't be recovered. 1: succeeded. For an example: int result = xmem_free(pool1, my_stct); if(!result) printf("Cannot be recovered.\n"); Destroy the Whole Pool void xmem_destroy_pool(xmem_pool_handle pool); Caution! This function will destroy the whole pool, freeing all your memory allocated by that pool, even if you haven't xmem_free yet. xmem_destroy_pool(pool1); xmem_destroy_pool(pool2);
用户评论