Lab 5: Writing a Dynamic Storage Allocator

Assigned Monday, November 25, 2013
Due Date Friday, December 6, 2013 at 5:00pm
Files lab5.tar.gz
Submissions Submit your completed mm.c file here.

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. It is quite involved. Start early!

Optional Practice Problems

We are providing some extra homework-style practice problems for memory allocation in case you find them helpful in preparing for lab 5. They will not be graded (no credit), they are just good practice. Read section 9.9 from the textbook for review. (Note "word" means 4 bytes for these problems.)

  1. Practice Problem 9.6
  2. Practice Problem 9.7
  3. Practice Problem 9.10
  4. Homework Problem 9.15
  5. Homework Problem 9.16

Instructions

Start by extracting lab5.tar.gz to a directory where you plan to do your work:

wget cs.washington.edu/education/courses/cse351/13au/labs/lab5/lab5.tar.gz
tar xzvf lab5.tar.gz

This will cause a number of files to be unpacked in a directory called lab5. The only file you will modify and turn in is mm.c.

(In the following instructions, we will assume that you are executing programs in your local directory on attu. For this lab, you can work anywhere there's a C compiler and make, but make sure your allocator works on attu, where we'll be testing it.)

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 we 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:

We will compare 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.

Provided Code

We 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:

In addition, we implement mm_init and provide two helper functions implementing important parts of the allocator:

Finally, we 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 use macros as well, though the ones already included in mm.c are the only ones we used in our sample solution, so it's possible without more. For more info on macros, check the GCC manual.

Additionally, for debugging purposes, you may want to print the contents of the heap. Here's code for a procedure to do so:


/* Print the heap by iterating through it as an implicit free list. */
static void examine_heap() {
  BlockInfo *block;

  /* print to stderr so output isn't buffered and not output if we crash */
  fprintf(stderr, "FREE_LIST_HEAD: %p\n", (void *)FREE_LIST_HEAD);

  for(block = (BlockInfo *)UNSCALED_POINTER_ADD(mem_heap_lo(), WORD_SIZE); /* first block on heap */
      SIZE(block->sizeAndTags) != 0 && block < mem_heap_hi();
      block = (BlockInfo *)UNSCALED_POINTER_ADD(block, SIZE(block->sizeAndTags))) {

    /* print out common block attributes */
    fprintf(stderr, "%p: %ld %ld %ld\t",
    (void *)block,
    SIZE(block->sizeAndTags),
    block->sizeAndTags & TAG_PRECEDING_USED,
    block->sizeAndTags & TAG_USED);

    /* and allocated/free specific data */
    if (block->sizeAndTags & TAG_USED) {
      fprintf(stderr, "ALLOCATED\n");
    } else {
      fprintf(stderr, "FREE\tnext: %p, prev: %p\n",
      (void *)block->next,
      (void *)block->prev);
    }
  }
  fprintf(stderr, "END OF HEAP\n\n");
}

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).

The Trace-driven Driver Program

The driver program mdriver.c in the lab5.tar.gz 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 are posted on attu (if you want to work on another computer, you can copy these files and then 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 we will use when we grade your submitted mm.c file.

The mdriver executable accepts the following command line arguments:

Programming Rules

Evaluation

Your grade will be calculated (as a percentage) out of a total of 60 points as follows:

Hints

Getting Started

Debugging

Heap Consistency Checker

This is an optional, but recommended, addition that will help you check to see if your allocator is doing what it should (or figure out what it's doing wrong if not). 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. In addition to the usual debugging techniques, you may find it helpful to write a heap checker that scans the heap and checks it for consistency.

Some examples of what a heap checker might check are:

Your heap checker will consist of the function int mm_check(void) in mm.c. Feel free to rename it, break it into several functions, and call it wherever you want. It should check any invariants or consistency conditions you consider prudent. It returns a nonzero value if and only if your heap is consistent. This is not required, but may prove useful. When you submit mm.c, make sure to remove any calls to mm_check as they will slow down your throughput.

Extra Credit

As optional extra credit, implement a final memory allocation-related function: mm_realloc. The signature for this function, which you will find in your mm.h file, is:

extern void* mm_realloc(void* ptr, size_t size);
Similarly, you should find the following in your mm.c file:
void* mm_realloc(void* ptr, size_t size) {
  // ... implementation here ...
}
To receive credit, you should follow the contract of the C library's realloc exactly (pretending that malloc and free are mm_malloc and mm_free, etc.). The man page entry for realloc says:
       The realloc() function changes the size of the memory block pointed to by
       ptr to size bytes.  The contents will be unchanged in the range from the
       start of the region up to the minimum of the old and new sizes.  If the
       new size is larger than the old size, the added memory will not be
       initialized.  If ptr is NULL, then the call is equivalent to
       malloc(size), for all values of size; if size is equal to zero, and ptr
       is not NULL, then the call is equivalent to free(ptr).  Unless ptr is
       NULL, it must have been returned by an earlier call to malloc(), calloc()
       or realloc().  If the area pointed to was moved, a free(ptr) is done.
A good test would be to compare the behavior of your mm_realloc to that of realloc, checking each of the above cases. Your implementation of mm_realloc should also be performant. Avoid copying memory if possible, making use of nearby free blocks. You should not use memcpy to copy memory; instead, copy WORD_SIZE bytes at a time to the new destination while iterating over the existing data.

To run tracefiles that test mm_realloc, compile using make mdriver-realloc. Then, run mmdriver-realloc with the -f flag to specify a tracefile, or first edit config.h to include additional realloc tracefiles in the default list.

Extra Extra Credit

Do NOT spend time on this part until you have finished and turned in the core assignment.

In this extra credit portion you will implement a basic mark and sweep garbage collector. Download lab5ec.tar.gz and expand it in a separate directory for now. There will be four files:

Some additional notes:

Submitting Your Work

Submit your mm.c file to the Catalyst Drop Box for this assignment.