113 lines
2.9 KiB
C
113 lines
2.9 KiB
C
#include <error.h>
|
|
#include <string.h>
|
|
#include "dtl.h"
|
|
|
|
/* Memory_info 结构 伪构造函数 */
|
|
static struct Memory_info *
|
|
memory_info_init(size_t size, struct Memory_info *next, const char *a);
|
|
|
|
/* Memory_status 结构初始化函数 */
|
|
static void
|
|
memory_status_init(void);
|
|
|
|
static struct Memory_status memory_status_dbtools = {0, 0, NULL};
|
|
|
|
void
|
|
memory_status_init(void)
|
|
{
|
|
memory_status_dbtools.all_size = 0;
|
|
memory_status_dbtools.count = 0;
|
|
memory_status_dbtools.front = memory_info_init(0, NULL, "root");
|
|
}
|
|
|
|
void*
|
|
__malloc(size_t size, const char *a)
|
|
{
|
|
/* 确保已经初始化 */
|
|
if(memory_status_dbtools.front == NULL)
|
|
memory_status_init();
|
|
|
|
struct Memory_info *it = memory_status_dbtools.front;
|
|
/* 寻找不大于当前内存块的第一个位置 */
|
|
while((it->next != NULL) && (it->next->size > size))
|
|
it = it->next;
|
|
|
|
/* 分配内存块 */
|
|
it->next = memory_info_init(size, it->next, a);
|
|
|
|
/* 分配成功 修改总数据 */
|
|
memory_status_dbtools.all_size += size;
|
|
memory_status_dbtools.count++;
|
|
|
|
return it->next->address;
|
|
}
|
|
|
|
|
|
void
|
|
__free(void *ptr)
|
|
{
|
|
/* 避免释放不存在的内存 */
|
|
if(NULL == ptr)
|
|
return;
|
|
|
|
/* 确保已经初始化 */
|
|
if(memory_status_dbtools.front == NULL)
|
|
memory_status_init();
|
|
|
|
struct Memory_info *it = memory_status_dbtools.front;
|
|
while(it->next != NULL) {
|
|
/* 找到对应的地址块信息就在信息链表中删除 */
|
|
if(ptr == it->next->address) {
|
|
struct Memory_info *temp = it->next->next;
|
|
memory_status_dbtools.all_size -= it->next->size;
|
|
memory_status_dbtools.count--;
|
|
|
|
free(ptr);
|
|
ptr = NULL;
|
|
free(it->next);
|
|
it->next = temp;
|
|
break;
|
|
}
|
|
it = it->next;
|
|
}
|
|
}
|
|
|
|
extern void
|
|
__display_memory_status(void)
|
|
{
|
|
printf("\n---Memory status---\n");
|
|
printf("All_size: %ld\n", memory_status_dbtools.all_size);
|
|
printf("count: %d\n", memory_status_dbtools.count);
|
|
|
|
printf("--- Stat Info ---\n");
|
|
struct Memory_info *it = memory_status_dbtools.front->next;
|
|
while(NULL != it) {
|
|
printf("%p\n", it->address);
|
|
printf("%ld\n", it->size);
|
|
printf(it->message);
|
|
printf("\n----------------\n");
|
|
it = it->next;
|
|
}
|
|
printf("\n\n");
|
|
}
|
|
|
|
|
|
struct Memory_info *
|
|
memory_info_init(size_t size, struct Memory_info *next, const char *a)
|
|
{
|
|
struct Memory_info *dst;
|
|
dst = (struct Memory_info*)malloc(sizeof(struct Memory_info));
|
|
if(NULL == dst)
|
|
perror("memory_info_init: malloc fail!");
|
|
|
|
dst->size = size;
|
|
dst->next = next;
|
|
if(size != 0) {
|
|
dst->address = malloc(size);
|
|
if(NULL == dst->address)
|
|
perror("memory_info_init: malloc fail!");
|
|
} else dst->address = NULL;
|
|
strncpy(dst->message, a, 31);
|
|
return dst;
|
|
}
|