有,51高俊峰 Linux高级架构师
作者徽:822135616
在編程中,為了避免由于頻繁的malloc/free產(chǎn)生內(nèi)存碎片,通常會(huì)在程序中實(shí)現(xiàn)自己的內(nèi)存管理模塊,即內(nèi)存池。內(nèi)存池的原理:程序啟動(dòng)時(shí)為內(nèi)存池申請(qǐng)一塊較大的內(nèi)存,在程序中使用內(nèi)存時(shí),都由內(nèi)存池進(jìn)行分配,不再使用的內(nèi)存交給內(nèi)存池回收,用于再次分配。內(nèi)存池一般會(huì)有如下的接口:memory_pool_init, memory_pool_malloc, memory_pool_free 和 memory_pool_destroy。memory_pool.h
#ifndef __MEMORY_POOL_H__
#define __MEMORY_POOL_H__
?
#define MAX_POOL_SIZE 1024 * 1024
#define BLOCK_SIZE 64
?
typedef struct memory_map_talbe
{
?char *p_block;
?int index;
?int used;
} Memory_Map_Table;
?
typedef struct memory_alloc_table
{
?char *p_start;
?int used;
?int block_start_index;
?int block_cnt;
}Memory_Alloc_Table;
?
typedef struct memory_pool
{
?char *memory_start;//內(nèi)存池起始地址, free整個(gè)內(nèi)存池時(shí)使用
?Memory_Alloc_Table *alloc_table;
?Memory_Map_Table *map_table;
?int total_size;
?int internal_total_size;
?int increment;
?int used_size;
?int block_size;
?int block_cnt;
?int alloc_cnt;
} Memory_Pool;
?
extern Memory_Pool *memory_pool_init(int size, int increment);
extern void *Memory_malloc(Memory_Pool *pool, int size);
extern void memory_free(Memory_Pool *pool, void *memory);
extern void memory_pool_destroy(Memory_Pool *pool);
?
#endif
?
memory_pool.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
?
#include "memory_pool.h"
總結(jié)
以上是生活随笔為你收集整理的有,51高俊峰 Linux高级架构师的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 黑马程序员—7k月薪面试题之交通灯管理系
- 下一篇: linux charg修改目录,Thin