Libevent Memory Mange
#include <event2/event.h>
#include <sys/types.h>
#include <stdlib.h>
/* This union's purpose is to be as big as the largest of all the
* types it contains. */
union alignment {
size_t sz;
void *ptr;
double dbl;
};
/* We need to make sure that everything we return is on the right
alignment to hold anything, including a double. */
#define ALIGNMENT sizeof(union alignment)
/* We need to do this cast‐to‐char* trick on our pointers to adjust
them; doing arithmetic on a void* is not standard. */
#define OUTPTR(ptr) (((char*)ptr)+ALIGNMENT)
#define INPTR(ptr) (((char*)ptr)‐ALIGNMENT)
static size_t total_allocated = 0;
static void *replacement_malloc(size_t sz)
{
void *chunk = malloc(sz + ALIGNMENT);
if (!chunk) return chunk;
total_allocated += sz;
*(size_t*)chunk = sz;
return OUTPTR(chunk);
}
static void *replacement_realloc(void *ptr, size_t sz)
{
size_t old_size = 0;
if (ptr) {
ptr = INPTR(ptr);
old_size = *(size_t*)ptr;
}
ptr = realloc(ptr, sz + ALIGNMENT); if (!ptr)
return NULL;
*(size_t*)ptr = sz;
total_allocated = total_allocated ‐ old_size + sz;
return OUTPTR(ptr);
}
static void replacement_free(void *ptr)
{
ptr = INPTR(ptr);
total_allocated ‐= *(size_t*)ptr;
free(ptr);
}
void start_counting_bytes(void)
{
event_set_mem_functions(replacement_malloc,
replacement_realloc,
replacement_free);
}/* We need to do this cast‐to‐char* trick on our pointers to adjust
them; doing arithmetic on a void* is not standard. */
#define OUTPTR(ptr) (((char*)ptr)+ALIGNMENT)
#define INPTR(ptr) (((char*)ptr)‐ALIGNMENT)
if (!chunk) return chunk; //这里如果分配失败直接返回NULL
total_allocated += sz; //这里在total_allocated里面加上sz
if (ptr) { //ptr本来就是就是一个memory 的指针
ptr = INPTR(ptr); // 然后得到 chunk 的指针
old_size = *(size_t*)ptr; //用old_size保存旧的memory的size
ptr = realloc(ptr, sz + ALIGNMENT); //重新分配 用realloc
return NULL; //这里其实可以返回 return ptr;
*(size_t*)ptr = sz; //然后把新分配的chunk 然后把sz赋给他
total_allocated = total_allocated ‐ old_size + sz; //减去旧的size然后 加上新分配的memory
return OUTPTR(ptr); //返回memory的指针
total_allocated ‐= *(size_t*)ptr; //减去memory的大小
free(ptr); //释放ptr所占的内存
2984



被折叠的 条评论
为什么被折叠?



