简易的字符串内存池实现

有很多这样的应用场景:不停的产生一些字符串,并串联在一起,最后一起输出。这种场景的特点是,最终字符串的长度是不确定的。借鉴ngx_poop_t的实现,做一个简单的内存池,代码如下:

typedef struct buf_list_s buf_list_t;
struct buf_list_s {
	buf_list_t *next;			/* 当一个用满时,重新申请一个,组成链表 */
	buf_list_t *current;		/* 当前在使用的 */
	char *str;				/* 内存池 */
	int size;
	int used;
	int resolution;			/* 当一个池中所剩的量小于该值时,则重新申请一个使用。该值与size值,可根据具体使用的场景,一次写入的长度来优化选择 */
} ;

buf_list_t* buf_init(int size,int resolution)
{
	buf_list_t *buf;
	buf = malloc(sizeof(buf_list_t));
	buf->next = NULL;
	buf->current = NULL;
	buf->size = size;
	buf->used = 0;
	buf->resolution = resolution;
	buf->str = malloc(size);
	memset(buf->str,'\0',size);
	return buf;
}

char *buf_sprintf(buf_list_t *head,char *fmt,...)		/* 类似于vsprintf,用起来方便 */
{
	buf_list_t *current;
	int lr;
	va_list args;
	
	current = head->current;
	if(current->size-current->used < current->resolution) {		/* 使用过程中,自动决定是否要新分配池 */
		current->next = buf_init(head->size,head->resolution);
		current = current->next;
		head->current = current;
	}
	va_start(args,fmt);
	vsprintf(current->str+current->used,fmt,args);
	va_end(args);
	lr = strlen(current->str+current->used);
	current->used += lr;


	return current->str+current->used-lr;
}

void buf_print(buf_list_t *head)
{
	while(head)
	{
		printf("%s",head->str);
		head = head->next;
	}
}

void buf_free(buf_list_t *head)
{
	buf_list_t *tmp;
	while(head)
	{
		free(head->str);
		tmp = head;
		head = tmp->next;
		free(tmp);
	}
}

这样,使用起来就很快捷方便了:

int main()
{
	buf_list_t *head=NULL;
	head = buf_init(100,15);
	head->current = head;

	while(1){
		buf_sprintf(head,"%d card(s)\n",cards);
	}
	buf_print(head);
	buf_free(head); 
	return 0;
}

         
         



           
           





           
           









           
           







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值