C Programer  - 讨论区

标题:APR Memory Pool模块编程示例

2014年01月10日 星期五 10:18

为了方便内存资源管理,APR提供了Memory Pool模块,使用此模块,可以创建内存池、子内存池,并可以在内存池销毁时回调之前注册的函数。APR的所有模块都统一使用Memory Pool来进行内存管理,可以这样说,使用APR进行编程,就可以基本告别malloc、free这些方法了。编程示例如下:

 

#include <stdio.h>
#include <apr.h>
#define APR_POOL_DEBUG 16
#include <apr_pools.h>
#include <apr_errno.h>
#include <apr_strings.h>


void apr_err(const char *s, apr_status_t rv)
{
    char buf[120];
    fprintf(stderr, "%s: %s (%d)\n", s, apr_strerror(rv, buf, sizeof buf), rv);
}

apr_status_t str_clean_up(void *s) {
    char *c=s;
    printf("I will clean up the string: %s\n",c);
    return APR_SUCCESS;
}

int main(int argc,char **argv) {
    apr_initialize();
    apr_pool_t *pool;
    apr_pool_create(&pool,NULL);
    apr_status_t st;

    apr_pool_t *subpool;
    apr_pool_create(&subpool,pool);
    char *u=apr_pcalloc(subpool,1024);
    strcpy(u,"xiaozhang");
    apr_pool_cleanup_register(subpool,u,str_clean_up,str_clean_up);

    char *s=apr_pcalloc(pool,1024);
    strcpy(s,"laomeng");
    apr_pool_cleanup_register(pool,s,str_clean_up,str_clean_up);

    char *p=apr_pcalloc(pool,1024);
    strcpy(p,"laozhang");
    apr_pool_cleanup_register(pool,p,str_clean_up,str_clean_up);

    apr_pool_destroy(pool);
    apr_terminate();
    return 0;
}

参考资料:

http://apr.apache.org/docs/apr/1.3/group__apr__pools.html

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号