有,51高俊峰 Linux高级架构师
作者徽:822135616
在編程中,為了避免由于頻繁的malloc/free產生內存碎片,通常會在程序中實現自己的內存管理模塊,即內存池。內存池的原理:程序啟動時為內存池申請一塊較大的內存,在程序中使用內存時,都由內存池進行分配,不再使用的內存交給內存池回收,用于再次分配。內存池一般會有如下的接口: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;//內存池起始地址, free整個內存池時使用
?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"
總結
以上是生活随笔為你收集整理的有,51高俊峰 Linux高级架构师的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑马程序员—7k月薪面试题之交通灯管理系
- 下一篇: linux 其他常用命令