Malloc Lab: 编写一个动态存储分配器
1. 简介
在这个实验中,你将为 C programs 编写一个 dynamic storage allocator
i.e. 你自己的malloc, free, realloc 程序(routines)
我们鼓励你去探索 the design space creatively
并能够实现一个 correct, efficient and fast 的 allocator
2. Hand Out Instructions
The only file you will be modifying and handing in is mm.c.
mdriver.c 是一个 驱动程序(driver program) 可以评估你的 solution 性能
使用命令 make
生成 driver code
使用命令./mdriver -V
去运行它 (The -V flag displays helpful summary information.)
将你的solution包含在mm.c中
3. How to Work on the Lab
Your dynamic storage allocator will consist of the following four functions, which are declared in mm.h
and defined in mm.c
int mm_init(void);
void *mm_malloc(size_t size);
void mm_free(void *ptr);
void *mm_realloc(void *ptr, size_t size);
The mm.c
file we have given you implements the simplest but still functionally correct malloc package that we could think of. Using this as a starting place, modify these functions (and possibly define other private static functions), so that they obey the following semantics:
mm_init
:Before callingmm_malloc mm_realloc mm_free
, 应用程序 (i.e., the trace-driven driver program that you will use to evaluate your implementation) 调用mm_init
去执行一些必须的初始化
比如分配初始的堆空间,如果初始化失败就会返回-1,成功返回0mm malloc
:mm_malloc程序返回一个指针 →分配一块至少 payload 为 bites 的块
所有分配块需要位于堆的范围之内,而且不要和其他已分配的块重叠
我们会将你的实现和标准C函数库(libc)中的malloc进行比较
因为libc中的malloc会返回对齐为8 bytes的 payload pointers
所以你的malloc实现也需要返回对齐为8bytes的指针mm_free
:mm_free程序释放 ptr所
没有返回值
这个程序只有在之前调用mm_malloc
或mm_realloc
时返回的
ptr(passed pointer)没有被释放时才会生效mm_realloc
:mm_realloc
程序指向一个已经分配的区域的指针
至少是size bites大小
有如下几个约束条件- 如果ptr为NULL,调用相当于mm_malloc(size);
- 如果size等于0,调用相当于mm_free(ptr);
- 如果ptr非NULL,那么它之前必定被mm_malloc或mm_realloc的调用返回
对mm_realloc的调用将ptr所指向的内存块空间的大小改为size bites
(The call to mm_realloc changes the size of the memory block pointed to by ptr (the old
block) to size bytes and returns the address of the new block.)