CSCI 237 :: Computer Organization (original) (raw)
CSCI 237
Computer Organization
Home |Lectures |Labs |CS@Williams
Lab 6: Writing a Dynamic Storage Allocator
Assigned | Apr 30/May 1, 2025 |
---|---|
Prelim Due Date | May 6/7, 2025 at 11:59pm. Submit your latest version of mm.c. |
Final Due Date | May 13/14, 2025 at 11:59pm. Submit your final version of mm.c. |
Files | <lab6.tar> |
Submissions | Submit your solutions using submit237 6 mm.c. If you work with a partner, only one submission per pair is required. |
Overview
In this lab, you will be writing a dynamic storage allocator for C programs, i.e., your own version of the malloc and free routines. This is a classic implementation problem with many interesting algorithms and opportunities to put several of the skills you have learned in this course to good use. It is tricky! Start early!
You may work with a partner on this lab. If you choose to work with a partner, make sure that both members of the group are contributing equally.
Learning Objectives
- Implement a memory allocator using an explicit free list.
- Examine how algorithm choice impacts tradeoffs between utilization and throughput.
- Read and modify a substantial C program.
- Improve your C programming skills including gaining more experience with structs, pointers, macros, and debugging.
Instructions
Start by extracting lab6.tar
to a directory where you plan to do your work:
$ wget http://www.cs.williams.edu/~jeannie/cs237/labs/lab6/lab6.tar
$ tar xvf lab6.tar
This will cause a number of files to be unpacked in a directory called lab6. The only file you will modify and turn in is mm.c
. You may find the short README
file useful to read.
Your dynamic storage allocator will consist of the following three functions (and several helper 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);
The mm.c
file I have given you partially implements an allocator using an explicit free list. Your job is to complete this implementation by filling out mm_malloc
and mm_free
. The three main memory management functions should work as follows:
mm_init
(provided): Before callingmm_malloc
ormm_free
, the application program (i.e., the trace-driven driver program that you will use to evaluate your implementation) callsmm_init
to perform any necessary initializations, such as allocating the initial heap area. The return value is -1 if there was a problem in performing the initialization, 0 otherwise.mm_malloc
: Themm_malloc
routine returns a pointer to an allocated block payload of at leastsize
bytes. (size_t
is a type for describing sizes; it's an unsigned integer that can represent a size spanning all of memory, so on x86_64 it is a 64-bit unsigned value.) The entire allocated block should lie within the heap region and should not overlap with any other allocated block.mm_free
: Themm_free
routine frees the block pointed to byptr
. It returns nothing. This routine is guaranteed to work only when the passed pointer (ptr
) was returned by an earlier call tomm_malloc
and has not yet been freed. These semantics match the the semantics of the corresponding malloc and free routines in libc. Typeman malloc
in the shell for complete documentation.
Your malloc implementation should always return 8-byte aligned pointers.
Provided Code
I define a BlockInfo
struct designed to be used as a node in a doubly-linked explicit free list, and the following functions for manipulating free lists:
BlockInfo* searchFreeList(int reqSize)
: returns a block of at least the requested size if one exists (andNULL
otherwise)void insertFreeBlock(BlockInfo* blockInfo)
: inserts the given block in the free list in LIFO (last in first out) mannervoid removeFreeBlock(BlockInfo* blockInfo)
: removes the given block from the free list
In addition, I implement mm_init
and provide two helper functions implementing important parts of the allocator:
void requestMoreSpace(int incr)
: enlarges the heap byincr
bytes (if enough memory is available on the machine to do so)void coalesceFreeBlock(BlockInfo* oldBlock)
: coalesces any other free blocks adjacent in memory tooldBlock
into a single new large block and updates the free list accordingly
Finally, I use a number of C preprocessor macros to extract common pieces of code (constants, annoying casts/pointer manipulation) that might be prone to error. Each is documented in the code. You are welcome to create your own macros as well, though the ones already included in mm.c
are the only ones I used in my sample solution, so it's possible without more. For more info on macros, check the GCC manual.
FREE_LIST_HEAD
: returns a pointer to the first block in the free list (the head of the free list)UNSCALED_POINTER_ADD
andUNSCALED_POINTER_SUB
: useful for doing pointer arithmetic without worrying about the size ofstruct BlockInfo
- Other short utilities for extracting the size field and determining block size
Additionally, for debugging purposes, you may want to print the contents of the heap. You can use the included examine_heap
function to do that.
Memory System
The memlib.c
package simulates the memory system for your dynamic memory allocator. In your allocator, you can call the following functions (if you use the provided code for an explicit free list, most uses of the memory system calls are already covered).
void* mem_sbrk(int incr)
: Expands the heap byincr
bytes, whereincr
is a positive nonzero integer and returns a pointer to the first byte of the newly allocated heap area. The semantics are identical to the Unixsbrk
function, except thatmem_sbrk
accepts only a positive nonzero integer argument. (Runman sbrk
if you want to learn more about what this does in Unix.)void* mem_heap_lo()
: Returns a pointer to the first byte in the heapvoid* mem_heap_hi()
: Returns a pointer to the last byte in the heap.size_t mem_heapsize()
: Returns the current size of the heap in bytes.size_t mem_pagesize()
: Returns the system's page size in bytes (4K on Linux systems).
The Trace-driven Driver Program
The driver program mdriver.c
in the lab6.tar
distribution tests your mm.c
package for correctness, space utilization, and throughput. Use the command make
to generate the driver code and run it with the command ./mdriver -V
(the -V
flag displays helpful summary information as described below).
The driver program is controlled by a set of trace files that it will expect to find in a subdirectory called traces
. The tar file provided to you should unpack into a directory structure that places the traces
subdirectory in the correct location relative to the driver. (If you want to move the trace files around, you can update the TRACEDIR path in config.h
). Each trace file contains a sequence of allocate and free directions that instruct the driver to call your mm_malloc
and mm_free
routines in some sequence. The driver and the trace files are the same ones I will use when I grade your submitted mm.c
file.
The mdriver
executable accepts the following command line arguments:
-t <tracedir>
: Look for the default trace files in directorytracedir
instead of the default directory defined inconfig.h
.-f <tracefile>
: Use one particulartracefile
for testing instead of the default set of tracefiles.-h
: Print a summary of the command line arguments.-l
: Run and measurelibc
malloc in addition to your malloc package.-v
: Verbose output. Print a performance breakdown for each tracefile in a compact table.-V
: More verbose output. Prints additional diagnostic information as each trace file is processed. Useful during debugging for determining which trace file is causing your malloc package to fail.
Programming Rules
- You should not change any of the interfaces in
mm.c
(e.g. names of functions, number and type of parameters, etc.). - You should not invoke any memory-management related library calls or system calls. This means you cannot use
malloc
,calloc
,free
,realloc
,sbrk
,brk
or any variants of these calls in your code. (You may use all the functions inmemlib.c
, of course.) - You are not allowed to define any global or
static
compound data structures such as arrays, structs, trees, or lists in yourmm.c
program. You are allowed to declare global scalar variables such as integers, floats, and pointers inmm.c
, but try to keep these to a minimum. (It is possible to complete the implementation of the explicit free list without adding any global variables.) - For consistency with the
malloc
implementation inlibc
, which returns blocks aligned on 8-byte boundaries, your allocator must always return pointers that are aligned to 8-byte boundaries. The driver will enforce this requirement for you.
Evaluation
Your grade will be calculated (as a percentage) out of a total of 55 points as follows:
- Correctness (45 points). You will receive 5 points for each test performed by the driver program that your solution passes. (9 tests)
- Performance (5 points). Performance represents a small portion of your grade. I am most concerned about the correctness of your implementation. For the most part, a correct implementation will yield reasonable performance. Two performance metrics will be used to evaluate your solution:
- Space utilization: The peak ratio between the aggregate amount of memory used by the driver (i.e., allocated via
mm_malloc
but not yet freed viamm_free
) and the size of the heap used by your allocator. The optimal ratio is 1,although in practice we will not be able to acheive that ratio. You should find good policies to minimize fragmentation in order to make this ratio as close as possible to the optimal. - Throughput: The average number of operations completed per second.
The driver program summarizes the performance of your allocator by computing a performance index, P, which is a weighted sum of the space utilization and throughput:
- Space utilization: The peak ratio between the aggregate amount of memory used by the driver (i.e., allocated via
P = 0.6U + 0.4 min (1, T/Tlibc)
where U is your space utilization, T is your throughput, and Tlibc is the estimated throughput of libc
malloc on your system on the default traces. The performance index favors space utilization over throughput. You will receive 5(P+ 0.1) points, rounded up to the closest whole point. For example, a solution with a performance index of 0.63 or 63% will receive 4 performance points. Our complete version of the explicit free list allocator has a performance index between just over 0.7 and 0.8; it would receive a full 5 points. Thus if you have a performance index GREATER THAN 0.7 (mdriver prints this as "70/100") then you will get the full 5 points for Performance. Observing that both memory and CPU cycles are expensive system resources, I adopt this formula to encourage balanced optimization of both memory utilization and throughput. Ideally, the performance index will reach P = 1 or 100%. To receive a good performance score, you must achieve a balance between utilization and throughput.
- Style (5 points).
- Your code should use as few global variables as possible (ideally none!).
- Your code should be as clear and concise as possible.
- You should use provided macros as appropriate.
- Since some of the unstructured pointer manipulation inherent to allocators can be confusing, short inline comments on steps of the allocation algorithms are also recommended. (These will also help us give you partial credit if you have a partially working implementation.)
- Each function should have a header comment that describes what it does and how it does it.
Hints
Getting Started
- Read these instructions.
- Read over the provided code.
- Take notes while doing the above.
- Draw some diagrams of what the data structures should look like before and after various operations.
Debugging
- Use the
mdriver
-f
option. During initial development, using tiny trace files will simplify debugging and testing. I have included two such trace files (short1-bal.rep
andshort2-bal.rep
) that you can use for initial debugging. - Use the
mdriver
-v
and-V
options. The-v
option will give you a detailed summary for each trace file. The-V
will also indicate when each trace file is read, which will help you isolate errors. - Compile with
gcc -g
and usegdb
. The-g
flag tellsgcc
to include debugging symbols, sogdb
can follow the source code as it steps through the executable. TheMakefile
should already be set up to do this. A debugger will help you isolate and identify out of bounds memory references. You can specify any command line arguments formdriver
after therun
command ingdb
e.g.run -f short1-bal.rep
. - Understand every line of the malloc implementation in the textbook. The textbook has a detailed example of a simple allocator based on an implicit free list. Use this as a point of departure. Don't start working on your allocator until you understand everything about the simple implicit list allocator.
- Write a function that treats the heap as an implicit list (see examine_heap above), and prints all header information from all the blocks in the heap. Using
fprintf
to print tostderr
is helpful here because standard error is not buffered so you will get output from your print statements even if the next statement crashes your program. - Encapsulate your pointer arithmetic in C preprocessor macros. Pointer arithmetic in memory managers is confusing and error-prone because of all the casting that is necessary. I have supplied macros that do this: see
UNSCALED_POINTER_ADD
andUNSCALED_POINTER_SUB
. - Start early, and good luck!
Resources