您的位置:首页 > 运维架构

Study from open source code -- malloc trace (1)

2010-08-19 17:47 441 查看
for working on fsck the disk mounted on board, i read the the code of the e2fsck, study some useful skills, such like this:

malloc_trace.

we malloc or free the memory in programes, some skills will be useful for us to debug

if want get more information, please 'man malloc_hook'

a example follw:

/*
* =====================================================================================
*
*       Filename:  mtrace.c
*
*    Description:  trace the malloc in heap, that may be helpful for our debugging
*
*        Version:  1.0
*        Created:  2010年08月19日 15时48分15秒
*       Revision:  none
*       Compiler:  gcc
*
*         Author:  StrongMouse (), inch.zheng@besovideo.com
*        Company:  Besovideo
*
* =====================================================================================
*/
#include <stdio.h>
#include <malloc.h>
typedef void * _ptr_t;
//global variable for storage the old hook
static void  (*tr_old_free_hook)(_ptr_t ptr, const void *caller);
static _ptr_t (*tr_old_malloc_hook)(size_t size, const void *caller);
static _ptr_t (*tr_old_realloc_hook)(_ptr_t ptr, size_t size, const void *caller);
//just as extern, decalare only
static void  my_free_hook(_ptr_t ptr, const void *caller);
static _ptr_t my_malloc_hook(size_t size, const void *caller);
static _ptr_t my_realloc_hook(_ptr_t ptr, size_t size, const void *caller);
static void  my_init_hook(void);
//malloc will call this function, once when implement of malloc func
void (*__malloc_initialize_hook)(void) = my_init_hook;
static void (my_init_hook)(void)
{
tr_old_free_hook = __free_hook;
__free_hook = my_free_hook;
tr_old_malloc_hook = __malloc_hook;
__malloc_hook = my_malloc_hook;
tr_old_realloc_hook = __realloc_hook;
__realloc_hook = my_realloc_hook;
printf("in func %s/n", __func__);
};
static void (my_free_hook)(_ptr_t ptr, const void *caller)
{
__free_hook = tr_old_free_hook;
printf("free the %p/n", ptr);
free(ptr);
__free_hook = my_free_hook;
}
static _ptr_t my_malloc_hook(size_t size, const void *caller)
{
_ptr_t hdr = NULL;
__malloc_hook = tr_old_malloc_hook;
hdr = malloc(size);
printf("malloc size %d %p/n", size, hdr);
__malloc_hook = my_malloc_hook;
return hdr;
}
static _ptr_t my_realloc_hook(_ptr_t ptr, size_t size, const void *caller)
{
_ptr_t hdr = NULL;
__realloc_hook = tr_old_realloc_hook;
hdr = realloc(ptr, size);
printf("realloc <%p> %p,%d/n", ptr, hdr, size);
__realloc_hook = my_realloc_hook;
return hdr;
}
int main(int argc, const char *argv[])
{
int i = 0;
_ptr_t ptr = NULL;
for(i = 0; i < 10; i++)
{
ptr = malloc(i);
free(ptr);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: