?自定义malloc和free函数代替系统函数
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int total = 0;
static int mem_max = 0;
void* __real_malloc(size_t size);
void __real_free(void *ptr);
malloc函数:
void* __wrap_malloc(size_t size)
{
if(size == 0){
printf("malloc size = 0 error \n");
return NULL;
}
char* ptr = __real_malloc(size + 4);
total += size;
*(int*)ptr = size;
ptr += 4;
if(mem_max < total)
mem_max = total;
return (void *)ptr;
}
free函数:
void __wrap_free(void *ptr)
{
if(!ptr){
printf("free NULL \n");
return;
}
char * realaddr = ptr;
int size = 0;
realaddr -= 4;
size = *((int*)realaddr);
total -= size;
__real_free(realaddr);
}
在代码流程中调用以下两个函数,打印当前内存消耗情况
int get_toal_mem()
{
printf("mem current used %d, mem peak %d\n",total,mem_max);
return total;
}
void print_mem_change(int mem_before)
{
if(mem_before > total){
printf("mem dec = %d##############\n",mem_before - total);
}else if(total > mem_before ){
printf("mem inc = %d##############\n",total - mem_before);
}else{
printf("mem not change@@@@@@@@@@@@@\n");
}
printf("mem before %d, mem current %d ------- mem_peak %d\n",mem_before,total,mem_max);
}
|