目标:实现一个放置策略为首次适配,并合策略为立即并合基于隐式空闲链表的内存分配器。
这里使用memlib.c包提供的存储器系统模型,该模型允许我们在不干涉已存在的malloc包的情况下运行分配器,也就是说封装了malloc函数。
memlib.h
void mem_init(void);
void *mem_sbrk(int incr);
memlib.c:(封装了malloc函数)
#include <stdio.h>
#include <stdlib.h>
#include "csapp.h"
#define MAX_HEAP (1 << 30)
static char *mem_heap; /* Points to first byte of heap */
static char *mem_brk; /* Points to last byte of heap plus 1 */
static char *mem_max_addr; /* Max legal heap addr plus 1*/
void mem_init(void)
{
mem_heap = (char *)Malloc(MAX_HEAP);
mem_brk = (char *)mem_heap;
mem_max_addr = (char *)(mem_heap + MAX_HEAP);
}
/*
* mem_sbrk - Simple model of the sbrk function. Extends the heap
* by incr bytes and returns the start address of the new area. In
* this model, the heap cannot be shrunk.
*/
void *mem_sbrk(int incr)
{
char *old_brk = mem_brk;
if ( (incr < 0) || ((mem_brk + incr) > mem_max_addr)) {
errno = ENOMEM;
fprintf(stderr, "ERROR: mem_sbrk failed. Ran out of memory...\n");
return (void *)-1;
}
mem_brk += incr;
return (void *)old_brk;
}
mm.h
/*************************************************************************
>