CS 105 Malloc Lab: Writing a Dynamic Storage Allocator See Web page for due date

Similar documents
CS 105 Malloc Lab: Writing a Dynamic Storage Allocator See Web page for due date

CSE 361S Intro to Systems Software Final Project

1 Introduction. 2 Logistics. 3 Hand Out Instructions

Spring 2016, Malloc Lab: Writing Dynamic Memory Allocator

ECE454, Fall 2014 Homework3: Dynamic Memory Allocation Assigned: Oct 9th, Due: Nov 6th, 11:59PM

CSE 351, Spring 2010 Lab 7: Writing a Dynamic Storage Allocator Due: Thursday May 27, 11:59PM

CSE 361 Fall 2017 Malloc Lab: Writing a Dynamic Storage Allocator Assigned: Monday Nov. 13, Due: Monday Dec. 05, 11:59PM

CS 3214, Fall 2015 Malloc Lab: Writing a Dynamic Storage Allocator Due date: November 16, 2014, 11:59pm

CS 213, Fall 2002 Malloc Lab: Writing a Debugging Dynamic Storage Allocator Assigned: Fri Nov. 1, Due: Tuesday Nov. 19, 11:59PM

CSCI 2021, Fall 2018 Malloc Lab: Writing a Dynamic Storage Allocator Assigned: Monday November 5th Due: Monday November 19th, 11:55PM

COMP 321: Introduction to Computer Systems

Writing a Dynamic Storage Allocator

CS201: Lab #4 Writing a Dynamic Storage Allocator

Project 2. Assigned: 02/20/2015 Due Date: 03/06/2015

CSCI0330 Intro Computer Systems Doeppner. Project Malloc. Due: 11/28/18. 1 Introduction 1. 2 Assignment Specification Support Routines 4

Project 4: Implementing Malloc Introduction & Problem statement

HW 3: Malloc CS 162. Due: Monday, March 28, 2016

Recitation #11 Malloc Lab. November 7th, 2017

ANITA S SUPER AWESOME RECITATION SLIDES

Lab 1: Dynamic Memory: Heap Manager

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

Assignment 5. CS/ECE 354 Spring 2016 DUE: April 22nd (Friday) at 9 am

Recitation #12 Malloc Lab - Part 2. November 14th, 2017

Recitation 11: More Malloc Lab

Machine Problem 1: A Simple Memory Allocator

Lecture 8 Dynamic Memory Allocation

CS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: November 16, 11:30 PM

My malloc: mylloc and mhysa. Johan Montelius HT2016

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th

Project 2 Overview: Part A: User space memory allocation

CS 105 Lab 1: Manipulating Bits

Project 3a: Malloc and Free

Dynamic Memory Allocation. Basic Concepts. Computer Organization 4/3/2012. CSC252 - Spring The malloc Package. Kai Shen

CS 33. Storage Allocation. CS33 Intro to Computer Systems XXVII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Dynamic Memory Allocation I

CS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: April 5, 11:30 PM

Dynamic Memory Allocation I Nov 5, 2002

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

Dynamic Memory Allocation

Limitations of the stack

Carnegie Mellon. Malloc Boot Camp. Stan, Nikhil, Kim

Dynamic Memory Allocation: Basic Concepts

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt

CS 429H, Spring 2012 Optimizing the Performance of a Pipelined Processor Assigned: March 26, Due: April 19, 11:59PM

Recitation 10: Malloc Lab

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

Lab Assignment 4: Code Optimization

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CSE351 Spring 2010 Final Exam (9 June 2010)

CS 2505 Fall 2018 Data Lab: Data and Bitwise Operations Assigned: November 1 Due: Friday November 30, 23:59 Ends: Friday November 30, 23:59

Creating a String Data Type in C

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

MCS-284, Fall 2018 Cache Lab: Understanding Cache Memories Assigned: Friday, 11/30 Due: Friday, 12/14, by midnight (via Moodle)

CS356: Discussion #12-13 Dynamic Memory and Allocation Lab. Marco Paolieri Illustrations from CS:APP3e textbook

Programming Standards: You must conform to good programming/documentation standards. Some specifics:

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

BIL220, Spring 2012 Data Lab: Manipulating Bits Assigned: Feb. 23, Due: Wed., Mar. 8, 23:59PM

CS 2505 Fall 2013 Data Lab: Manipulating Bits Assigned: November 20 Due: Friday December 13, 11:59PM Ends: Friday December 13, 11:59PM

Lab 03 - x86-64: atoi

Memory management. Johan Montelius KTH

In Java we have the keyword null, which is the value of an uninitialized reference type

ECEn 424 Data Lab: Manipulating Bits

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Programming Tips for CS758/858

mmalloc The GNU memory-mapped malloc package Fred Fish Cygnus Support Mike Haertel Free Software Foundation

Dynamic Memory Allocation: Basic Concepts

Dynamic Memory Allocation

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CS 11 C track: lecture 5

Heap Management portion of the store lives indefinitely until the program explicitly deletes it C++ and Java new Such objects are stored on a heap

Project #1: Tracing, System Calls, and Processes

Review! Lecture 5 C Memory Management !

CSE351 Spring 2010 Final Exam (9 June 2010)

CS61C : Machine Structures

COSC Software Engineering. Lecture 16: Managing Memory Managers

Advanced Memory Allocation

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

10.1. CS356 Unit 10. Memory Allocation & Heap Management

Optimizing Dynamic Memory Management

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

ICS(II), Fall 2017 Cache Lab: Understanding Cache Memories Assigned: Thursday, October 26, 2017 Due: Sunday, November 19, 2017, 11:59PM

CS61C : Machine Structures

CS61C : Machine Structures

CS61 Section Notes. Section 5 (Fall 2011) Topics to be covered Common Memory Errors Dynamic Memory Allocation Assignment 3: Malloc

CS201 Some Important Definitions

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

15-213/18-213/15-513, Spring 2018 C Programming Lab: Assessing Your C Programming Skills

ECEn 424 The Performance Lab: Code Optimization

PROJECT 2 - MEMORY ALLOCATOR Computer Systems Principles. October 1, 2010

Memory Allocation. Copyright : University of Illinois CS 241 Staff 1

Programming Assignment III

2/9/18. Secure Coding. CYSE 411/AIT681 Secure Software Engineering. Agenda. Dynamic Memory Interface. Dynamic Memory Interface

Process s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty

Data Lab: Manipulating Bits

A Capacity: 10 Usage: 4 Data:

Dynamic Memory Allocation. Zhaoguo Wang

Transcription:

CS 105 Malloc Lab: Writing a Dynamic Storage Allocator See Web page for due date 1 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. 2 Logistics As usual, you must work in pairs. Any clarifications and revisions to the assignment will be e-mailed to the class list or posted on the course Web page. 3 Handout Instructions Start by downloading malloclab-handout.tar from the Web page to a protected directory in which you plan to do your work. Then 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 program is a driver program that allows you to evaluate the performance of your solution. 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 with other labs, mm.c contains a C structure named team, which you should fill in with information about your programming team. Do this right away so you don t forget. When you have completed the lab, you will submit only one file (mm.c), which contains your solution. 4 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. 1

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 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 initialization, such as allocating the initial heap area. The return value should be 0 if all was OK, and -1 if there was a problem during initialization. Note: mm init may be called more than once by the driver. It should not remember any external state, and should not assume that it is only called once. Each call to mm init should reset the allocator, forgetting everything that has gone before. mm malloc: The mm malloc routine returns a pointer to an allocated block of at least size bytes. The entire allocated block should lie within the heap region and should not overlap with any other allocated chunk. Note that the returned value should point to the payload the area available for use by the caller rather than to whatever header you might choose to put on the block. We will comparing your implementation to the version of malloc supplied in the standard C library (libc). The libc malloc always returns payload pointers that are aligned to 8 bytes, which is excessive on Linux; your malloc implementation can gain a few utilization points by aligning only to 4 bytes. In the Linux specification, it is legal to allocate 0 bytes; your implementation should behave gracefully in this case. It is up to you whether to return NULL or to return a non-null pointer that can legally be passed to mm free. 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. In the Linux specification, NULL can be passed to free. You can write mm free to accept NULL pointers, but the test driver will never exercise this case. mm realloc: The mm realloc routine returns a pointer to an allocated region of at least size bytes with the following constraints. If ptr is NULL, the call is equivalent to mm malloc(size); If size is equal to zero, the call is equivalent to mm free(ptr); If ptr is not NULL, it must have been returned by an earlier call to either 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 2

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. Type man malloc to the shell for complete documentation. 5 Some Notes on the Textbook The sample code in the textbook, while useful as an overview, should not be followed slavishly. In particular, the GET, PUT, NEXT BLKP, and PREV BLKP macros given on page 746 are an extremely bad idea that will get you into trouble and lead to much lost debugging time. Instead, you should follow the example in the provided mm.c, which uses a C structure to describe the block header, and then uses well defined macros to convert payload pointers into header pointers and vice versa. The MAX, PACK, GET SIZE, and GET ALLOC macros are the only sensible ones on that page. (CHUNKSIZE is an acceptable idea, though it is commented incorrectly.) Also, the code for extend_heap on page 746 is incorrect. Since extend_heap returns -1 on failure, and since many valid pointers are negative when cast to int, the test on line 8 should check for equality to -1: if ((int)(bp = mem_sbrk(size)) == -1) Actually, good style would break this into two much more readable lines: bp = mem_sbrk(size); if ((int)bp == -1) 6 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 write a heap checker that scans the heap and checks it for consistency. Some examples of what a heap checker might check are: Is every block in the free list marked as free? 3

Are there any contiguous free blocks that somehow escaped coalescing? Is every free block actually in the free list? Do the pointers in the free list point to valid free blocks? Do any allocated blocks overlap? Do the pointers in a heap block point to valid heap addresses? Your heap checker will consist of the function int mm check(void) in mm.c. It will check any invariants or consistency conditions you consider prudent. It returns a nonzero value if and only if your heap is consistent. You are not limited to the listed suggestions nor are you required to check all of them. You are encouraged to print out error messages when mm check fails. This consistency checker is for your own debugging during development. When you submit mm.c, make sure to remove any calls to mm check as they will slow down your throughput. Style points will be given for your mm check function. Make sure to put in comments and document what you are checking. 7 Support Routines The memlib.c package simulates the memory system for your dynamic memory allocator. You can invoke the following functions in memlib.c: 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. Note: your allocator should not assume that the memory returned by mem sbrk has any particular contents. Specifically, the memory might not be initialized to zero. void *mem heap lo(void): Returns a generic pointer to the first byte in the heap. void *mem heap hi(void): Returns a generic pointer to the last byte in the heap. size t mem heapsize(void): Returns the current size of the heap in bytes. size t mem pagesize(void): Returns the system s page size in bytes (4K on Linux systems). 8 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 commands that instruct the driver to call your mm malloc, mm realloc, 4

and mm free routines in some sequence. The driver and the trace files are the same ones we will use when we grade your submission mm.c file. The driver mdriver.c accepts the following command line arguments: -t <tracedir>: Look for the default trace files in directory tracedir instead of the default directory compiled into the program. -f <tracefile>: Use one particular tracefile for testing instead of the default set of trace files. -h: Print a summary of the command line arguments. -l: Run and measure libc malloc in addition to your own malloc package. -v: Verbose output. Print a performance breakdown for each trace file 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. 9 Programming Rules You should not change any of the interfaces in mm.c. You should not invoke any memory-management-related library calls or system calls. This excludes the use of malloc, calloc, free, realloc, sbrk, brk, mmap, or any variants of these calls in your code. You are allowed to define global or static scalar or compound data structures, such as integers, arrays, structs, trees, or lists in your mm.c program. (However, note that variable-sized structures, such as trees and lists, inherently can t be defined as static objects.) Your allocator must always return pointers that are aligned to 4-byte boundaries. The driver will enforce this requirement for you. 10 Evaluation You will receive zero points if you break any of the rules or your code is buggy and crashes the driver. Otherwise, your grade will be calculated as follows: Correctness (20 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. Performance (35 points). Two performance metrics will be used to evaluate your solution: 5

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. 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 ( ) T P = wu + (1 w) min 1, where w = 0.6, U is your space utilization, T is your throughput, and T libc is the estimated throughput of libc malloc on your system on the default traces. 1 The purpose of the min is to keep you from going overboard in trying to outperform the libc allocator. Note that the performance index favors space utilization over throughput, since w > 0.5. Since both memory and CPU cycles are expensive system resources, we adopted this formula to encourage balanced optimization. Ideally, the performance index would reach 1.0 or 100%, though that figure is unachievable in practice. Since each metric will contribute at most w and 1 w, respectively, to the performance index, you should not go to extremes to optimize either memory utilization or throughput at the expense of the other. To receive a good score, you must achieve a balance. Style (10 points). Your code should be properly decomposed into functions and use as few static or global variables as possible. (You will probably need at least one static to keep track of details about the heap.) 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 preceded by a header comment that describes what the function does. Each function should have a header comment that describes what it does and how it does it. 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. T libc 11 Submission Instructions Submit only mm.c, using cs105submit. For convenience, typing make submit will submit for you. You may submit your solution for testing as many times as you wish up until the due date. When you are satisfied with your solution, submit it again. Only the last version you submit will be graded. 1 The value for T libc is a constant in the driver that was established when the lab was set up. 6

Note that the final grading will be done on Wilkes. While it is possible to run your allocator on other machines (including your own), the score generated by mdriver may be different because of speed differences. Therefore, be sure to test your allocator on Wilkes to be sure you will get the grade you think you deserve. 12 Hints 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,2-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. If you give -V instead, the driver will also indicate when each trace file is read, which will help you isolate errors. Change your Makefile to replace -O2 with -g so you can use a debugger. A debugger will help you isolate and identify out of bounds memory references. Only switch back to -O2 after your code is working. 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. Encapsulate your pointer arithmetic in C preprocessor macros. Pointer arithmetic in memory managers is confusing and error-prone because of all the type-casting that is necessary. You can reduce the complexity significantly by writing macros for your pointer operations. See the text for examples. 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. Use a profiler. You may find the gprof tool helpful for optimizing performance. 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! 7