编译时ld选项中增加
-Wl,--wrap=malloc -Wl,--wrap=free
注意编译选项中优化处理(-O2等参数改成-O0)
#include <stdio.h>
#include <time.h>
void *__real_malloc(size_t size);
void __real_free(void *ptr);
typedef struct _mem_manager_t_
{
void *p;
size_t size;
unsigned int time;
struct _mem_manager_t_ *next;
}mem_manager_t;
static mem_manager_t mem_head;
unsigned int os_get_system_time(void)
{
struct timespec time = {0, 0};
clock_gettime(CLOCK_MONOTONIC, &time);
return time.tv_sec * 1000 + time.tv_nsec / 1000000;
}
void save_malloc_node(void *p_str, size_t size)
{
if(p_str == NULL)
return;
mem_manager_t *mem_node = NULL;
mem_node = __real_malloc(sizeof(mem_manager_t));
if(mem_node)
{
mem_node->p = p_str;
mem_node->size = size;
mem_node->time = os_get_system_time();
mem_node->next = mem_head.next;
mem_head.next = mem_node;
}
}
void free_malloc_node(void *p_str)
{
mem_manager_t *mem_node = NULL;
mem_manager_t *pre_node = NULL;
if(p_str == NULL)
return;
for(mem_node = mem_head.next, pre_node = &mem_head; mem_node != NULL; pre_node = mem_node, mem_node = mem_node->next)
{
if(mem_node->p == p_str)
{
pre_node->next = mem_node->next;
__real_free(mem_node);
break;
}
}
}
void check_mem_node(void)
{
mem_manager_t *mem_node = NULL;
for(mem_node = mem_head.next; mem_node != NULL; mem_node = mem_node->next)
{
printf("\033[32m[%s:%d]\033[36m time = %u, ptr = %p, size = %zu\033[0m\n", __FUNCTION__, __LINE__, mem_node->time, mem_node->p, mem_node->size);
}
}
void *__wrap_malloc(size_t c)
{
void *p = NULL;
p = __real_malloc(c);
save_malloc_node(p, c);
return p;
}
void __wrap_free(void *ptr)
{
if(ptr)
__real_free(ptr);
free_malloc_node(ptr);
}