用c语言实现一个完整的内存池 包括例子
时间: 2024-02-10 12:40:47 浏览: 66
以下是一个简单的内存池实现,包括初始化、申请内存、释放内存等基本操作。同时也提供了一个简单的例子,用于演示如何使用内存池。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct mem_pool_s {
char *start; /* 内存池起始地址 */
char *end; /* 内存池结束地址 */
char *current; /* 当前可分配的地址 */
int size; /* 内存池大小 */
} mem_pool_t;
/* 初始化内存池 */
mem_pool_t *mem_pool_init(int size) {
mem_pool_t *pool = (mem_pool_t *)malloc(sizeof(mem_pool_t));
if (pool == NULL) {
return NULL;
}
pool->start = (char *)malloc(size);
if (pool->start == NULL) {
free(pool);
return NULL;
}
pool->end = pool->start + size;
pool->current = pool->start;
pool->size = size;
return pool;
}
/* 申请内存 */
void *mem_pool_alloc(mem_pool_t *pool, int size) {
if (pool == NULL || size <= 0) {
return NULL;
}
char *p = pool->current;
if (p + size > pool->end) {
return NULL;
}
pool->current = p + size;
return p;
}
/* 释放内存 */
void mem_pool_free(mem_pool_t *pool, void *ptr) {
if (pool == NULL || ptr == NULL) {
return;
}
if (ptr < pool->start || ptr > pool->end) {
return;
}
pool->current = (char *)ptr;
}
int main() {
mem_pool_t *pool = mem_pool_init(1024);
if (pool == NULL) {
printf("Failed to create memory pool\n");
return -1;
}
char *str1 = (char *)mem_pool_alloc(pool, 10);
if (str1 == NULL) {
printf("Failed to allocate memory\n");
return -1;
}
strcpy(str1, "Hello");
printf("%s\n", str1);
char *str2 = (char *)mem_pool_alloc(pool, 10);
if (str2 == NULL) {
printf("Failed to allocate memory\n");
return -1;
}
strcpy(str2, "World");
printf("%s\n", str2);
mem_pool_free(pool, str1);
mem_pool_free(pool, str2);
free(pool->start);
free(pool);
return 0;
}
```
这个例子中,我们首先创建了一个大小为1024的内存池,然后分别申请了两块大小为10字节的内存,并向其中写入了字符串。接着,我们释放了这两块内存,并销毁了内存池。
阅读全文