CSC374, Spring 2010 Lab 2

Malloc Lab: Writing a Dynmaic Storage Allocator
Assigned: Friday, May 7
Version 1 Due: Friday, May 21, 11:59PM
Final Version Due: Friday May 28, 11:59PM

Contact your instructor (glancast@cs.depaul.edu) for advice/questions about this lab.


Introduction

In this lab you will be writing a dynamic storage allocator for C programs, i.e., your own version of the malloc, free and realloc routines. You are encouraged to explore the design space creatively and implement an allocator that is correct, efficient and fast.

Logistics

You may work in a group of up to two people. Any clarifications and revisions to the assignment will be posted on the course Web page.

Hand Out Instructions

On the CDM Linux machine, copy the malloclab-handout.tar file to a directory in your account.
Change to that directory and type

	cp ~glancast/374class/malloclab-handout.tar .
      

Or on your own Linux machine, open a terminal window, change to a directory where you want the tar file and copy the malloclab-handout.tar file from the class web site using wget:


	wget http://condor.depaul.edu/~glancast/374class/hw/malloclab-handout.tar

      

After copying malloclab-handout.tar to the directory in which you plan to work, give the command:

	tar xvf malloclab-handout.tar 
      

This will cause a number of files to be unpacked into the directory. The only file you will be modifying and handing in is mm.c.

The mdriver.c file included in the handout contains the main function and is a driver program that allows you to evaluate the performance of your solution.

Compiling

Use the command

	make	
      

to compile your mm.c file, the supporting .c files, the mdriver.c driver code and build the executable file mdriver.

Running

To run mdriver on the one of the 11 provided test trace files:

	make test0
	or 
	make test1
	or
	...
	make test10	
      

You can also run mdriver without the make command. This might be useful to run mdriver on a small trace file for debugging purposes. To run mdriver (without make) on a trace file, type:

	mdriver -V -f <file>
      

(Replace <file> by the name or path to an actual trace file. 11 trace files are provided and it is easy to write your own small test trace files.)

The -V flag displays helpful summary information. All flag options can be displayed by typing

	mdriver -h      
      

This will display the options:

	Options:
	-a         Don't check the team structure.
	-f file    Use file as the trace file.
	-g         Generate summary info for autograder.
	-h         Print this message.
	-l         Run libc malloc as well.
	-t dir     Directory to find default traces.
	-v         Print per-trace performance breakdowns.
	-V         Print additional debug info.
	-d n       Omit timing, debug = n. (E.g. -d 1 sets debug = 1)
	Use to conditionally execute some code:
	if ( debug == 1 ) {... }
      

Looking at the file mm.c you'll notice a C structure team into which you should insert the requested identifying information about the one or two individuals comprising your programming team. Do this right away so you don't forget.

When you have completed the lab, you will hand in only one file (mm.c), which contains your solution.

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 initial version of mm.c file provided for you implements the implicit free list (essentially the same as in the text) that includes these additional helper functions used to implement the four required functions:

	static void *extend_heap(size_t words);
	static void place(void *bp, size_t asize);
	static void *find_fit(size_t asize);
	static void *coalesce(void *bp);
      

The following functions are also included, but they are only for debugging your heap. (You should remove all calls to these functions when checking for speed and when you submit your solution!)

	static void printblock(void *bp); 
	static void checkblock(void *bp);
	static void mm_checkheap(int);
      

You may use the mm.c file provided as a starting place, modify the functions above (and possibly define other private static functions and macros), so that they obey the following semantics:

  1. mm_init: Before calling mm_malloc, mm_realloc or mm_free, the application program (i.e., the trace-driven driver program that you will use to evaluate your implementation) calls mm_init to perform any necessary initializations, such as allocating the initial heap area. The return value should be -1 if there was a problem in performing the initialization, 0 otherwise.

  2. mm_malloc: The mm_malloc(size) routine returns a pointer to an allocated block payload of at least size bytes. The entire allocated block should lie within the heap region and should not overlap with any other allocated block.

    We will comparing your implementation to the version of malloc supplied in the standard C library (libc). Since the libc malloc always returns payload pointers that are aligned to 8 bytes, your malloc implementation should do likewise and always return 8-byte aligned pointers.

  3. mm_free: The mm_free routine frees the block pointed to by ptr. It returns nothing. This routine is only guaranteed to work when the passed pointer (ptr) was returned by an earlier call to mm_malloc or mm_realloc and has not yet been freed.
  4. mm_realloc: The mm_realloc routine returns a pointer to an allocated region of at least size bytes with the following constraints.
    1. if ptr is NULL, the call is equivalent to mm_malloc(size);
    2. if size is equal to zero, the call is equivalent to mm_free(ptr);
    3. if ptr is not NULL, it must have been returned by an earlier call to mm_malloc or mm_realloc. 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. Notice that the address of the new block might be the same as the old block, or it might be different, depending on your implementation, the amount of internal fragmentation in the old block, and the size of the realloc request.

      The contents of the new block are the same as those of the old ptr block, up to the minimum of the old and new sizes. Everything else is uninitialized. For example, if the old block is 8 bytes and the new block is 12 bytes, then the first 8 bytes of the new block are identical to the first 8 bytes of the old block and the last 4 bytes are uninitialized. Similarly, if the old block is 8 bytes and the new block is 4 bytes, then the contents of the new block are identical to the first 4 bytes of the old block.

These semantics match the the semantics of the corresponding libc malloc, realloc, and free routines. See the man page for malloc for complete documentation.

Heap Consistency Checker

Dynamic memory allocators are notoriously tricky beasts to program correctly and efficiently. They are difficult to program correctly because they involve a lot of untyped pointer manipulation. You will find it very helpful to use a heap checker that scans the heap and checks it for consistency.

Some examples of what a heap checker might check are:

The mm_checkheap(int verbose) function included in the initial version of mm.c checks the following:

If verbose is not 0, mm_checkheap also calls printblock(void *bp) to print the address, bp, of the payload and the block's header and footer.

If you add pointers to free blocks, you will want to modify printblock to print those pointers as well if the block bp is free.

The mm_checkheap function is for your own debugging during development. When you submit mm.c, make sure to remove any calls to mm_checkheap as they will slow down your throughput.

Note that calls to mm_checkheap will generate entirely too much output for the test traces. It is probably only appropriate for small trace files constructed for debugging with only a few allocation, free requests. To be able to switch between printing the heap without having to recompile, call mm_checkheap only if the global variable 'debug' is not 0:

	if ( debug ) {
	mm_checkheap(debug);
	}	
      

The global variable 'debug' is 0 by default, but can be set to a different value with the -d option to mdriver:

	mdriver -V -d 1 -f mytrace.rep	
      

(mytrace.rep is not provided; you can/should write your own small trace file for debugging)

Support Routines

The memlib.c package simulates the memory system for your dynamic memory allocator. You can invoke the following functions in memlib.c:

  1. void *mem_sbrk(int incr):

    Expands the heap by incr bytes, where incr is a positive non-zero integer and returns a generic pointer to the first byte of the newly allocated heap area. The semantics are identical to the Unix sbrk function, except that mem_sbrk accepts only a positive non-zero integer argument.

  2. void *mem_heap_lo(void):
    Returns a generic pointer to the first byte in the heap.
  3. void *mem_heap_hi(void):
    Returns a generic pointer to the last byte in the heap.
  4. size_t mem_heapsize(void):
    Returns the current size of the heap in bytes.
  5. size_t mem_pagesize(void):
    Returns the system's page size in bytes (4K on Linux systems).

The functions mm_init and extend_heap already call mem_sbrk to get initial and additional heap memory as needed. You may not need to call the memlib functions directly from any other functions. Indeed it is recommended that you only call extend_heap to get any additional heap memory.

The Trace-driven Driver Program

The driver program mdriver.c in the malloclab-handout.tar distribution tests your mm.c package for correctness, space utilization, and throughput. The driver program is controlled by a set of trace files that are included in the malloclab-handout.tar distribution. Each trace file contains a sequence of allocate, reallocate, and free directions that instruct the driver to call your mm_malloc, mm_realloc, and mm_free routines in some sequence. The driver and the trace files are the same ones we will use when we grade your handin mm.c file.

The driver mdriver.c accepts the following command line arguments:
  1. -t tracedir:
    Look for the default trace files in directory tracedir instead of the default directory defined in config.h.
  2. -f tracefile Use one particular tracefile for testing instead of the default set of tracefiles.
  3. -h: Print a summary of the command line arguments.
  4. -l: Run and measure libc malloc in addition to the student's malloc package.
  5. -v: Verbose output. Print a performance breakdown for each tracefile in a compact table.
  6. -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

  1. You should not change any of the interfaces in mm.c.
  2. You should not invoke any memory-management related library calls or system calls. This excludes the use of malloc, calloc, free, realloc, sbrk, brk or any variants of these calls in your code.
  3. You are not allowed to define any global or static compound data structures such as arrays, structs, trees, or lists in your mm.c program. However, you are allowed to declare global scalar variables such as integers, floats, and pointers in mm.c.
  4. For consistency with the libc malloc package, 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

You will receive zero points if you break any of the rules or your code is buggy and crashes the driver and you will need to fix the problems. This must be done before you submit your final version. Otherwise, your grade will be calculated as follows:

  1. Correctness (50 points). You will receive full points if your solution passes the correctness tests performed by the driver program. You will receive partial credit for each correct trace.
  2. Performance (150 points).

    Two performance metrics will be used to evaluate your solution:

    1. Space utilization: The peak ratio between the aggregate amount of memory used by the driver (i.e., allocated via mm_malloc or mm_realloc but not yet freed via mm_free) and the size of the heap used by your allocator. The optimal ratio equals to 1. You should find good policies to minimize fragmentation in order to make this ratio as close as possible to the optimal.
    2. 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:

    	    P = 0.60*U + 0.40*min(1, T/600) 
    	  

    where U is your space utilization, T is your throughput (Kilo ops per second = Kops), and 600 Kops is a guess at the throughput of libc malloc on the default traces.

    Getting the utilization score high is the proper goal. Once the utilization is good, it is usually not hard to devise ways to improve the throughput speed. If the throughput is above 600Kops, the score does not improve since the minumum of 1 and T/600 is used to compute the throughput part of your score.

    Ideally, the performance index will reach 100%. Since each metric will contribute at most 60% and 40% to the performance index, respectively, you should not go to extremes to optimize either the memory utilization or the throughput only. To receive a good score, you must achieve a balance between utilization and throughput. But getting a good memory utilization score should get higher priority.

  3. Style (10 points)
    1. Your code should be decomposed into functions and use as few global variables as possible.
    2. Your code should begin with a header comment that describes the structure of your free and allocated blocks, the organization of the free list, and how your allocator manipulates the free list. each function should be preceeded by a header comment that describes what the function does.
    3. Each subroutine should have a header comment that describes what it does and how it does it.
    4. Your heap consistency checker mm_check should be thorough and well-documented.

    You will be awarded 5 points for a good heap consistency checker and 5 points for good program structure and comments.

Handin Instructions

On CDM Linux servers, change to the directory with your mm.c file and submit it typing:

	make handin
      

If you are using your own Linux machine, submit your mm.c file to the Course Online site for assignment lab2.

You may submit your solution early if you have questions, but you must submit an initial version (working or not) by the version 1 due date. The (possibly revised) final version should be submitted by the final version due date.

Make sure you test your files locally. If you test your files on the CDM machines, the grade you get from mdriver is representative of the grade you will receive when you submit your solution.

Hints

  1. Use the mdriver -f option. During initial development, using tiny trace files will simplify debugging and testing. We have included two such trace files ( short1-bal.rep and short2-bal.rep) that you can use for initial debugging.
  2. 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.
  3. Compile with gcc -g and use a debugger. A debugger will help you isolate and identify out of bounds memory references.
  4. 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 is a point of departure. Don't start working on your allocator until you understand everything about the simple implicit list allocator.
  5. 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. You can reduce the complexity significantly by writing macros for your pointer operations. See the text for examples.
  6. Do your implementation in stages. The first 9 traces contain requests to malloc and free. The last 2 traces contain requests for realloc, malloc, and free. We recommend that you start by getting your malloc and free routines working correctly and efficiently on the first 9 traces. Only then should you turn your attention to the realloc implementation. For starters, build realloc on top of your existing malloc and free implementations. But to get really good performance, you will need to build a stand-alone realloc.
  7. Use a profiler. You may find the gprof tool helpful for optimizing performance.
  8. Start early! It is possible to write an efficient malloc package with a few pages of code. However, we can guarantee that it will be some of the most difficult and sophisticated code you have written so far in your career. So start early, and good luck!