Build your own malloc!
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
In class, we learned about the functions malloc and free which let us allocate and free memory on the heap. Now, we are going to implement our own version of these two functions! Hopefully, this will help you gain appreciation for how pretty much everything in C is built on top of two very simple ideas: (1) C is just a convenient way of writing assembly, and (2) In assembly, you are the one in control of all the memory.
Plan of attack
What is the heap? The heap is simply an area of memory designated for the very purpose of dynamically allocating/freeing memory during the execution of the program. Heap memory is provided by the operating system, and it is completely up to us to manage and use.
To request memory from operating systems, we use something called "system calls." The function malloc in C's standard library does the job of requesting memory for us. It also does all the management behind the scenes, to "allocate" and "free" blocks of specific sizes we want and give us the pointer to those blocks.
In summary, here is how malloc works:
- It finds an unused, contiguous block of heap memory that's large enough to satisfy the request, requesting extra memory from the OS if there is not enough space.
- It records internal information, denoting it has allocated that block, so it does not accidentally give away that chunk of memory again.
- It returns the pointer to the block for the user to use.
Dealing with system calls is outside the scope of this class (You will see this in 6.191!), so to simulate this process, we will simply create a huge global array called, wait for it... heap! (Also, by "huge," I mean something like a few million bytes.)
char heap[HEAPSIZE];
To help us keep track of all the allocations done so far, we create an array of struct block (aliased block_t), called blocks.
typedef struct block {
char *start;
int length;
int in_use;
} block_t;
block_t blocks[NUMBLOCKS];
Each "block" denotes the use of memory starting at start, up to a total of length bytes. We do not know how many blocks we will need, but we need to allocate memory for storing this information anyway, so we choose an arbitrary number (NUMBLOCKS) as a limit for how many blocks can be allocated at the same time. Only the entries with in_use value of 1 are considered, and the rest are ignored. Initially, all of them have in_use equals 0.
Of course, this means our "dynamic" memory allocation isn't so dynamic. We only have fixed amount of memory to give away, and we can only allocate so many blocks at once. But! In the real world, resources are finite, so is our time. So, we will just conveniently ignore this issue and focus on the "management" aspect of malloc and free.
Finally, we define an array of booleans called allocated (stored as an int array where 0 is false and 1 is true) to help us keep track of memory that has been given away. For example, if allocated[3] is true, this means &heap[3] is currently in use.
int allocated[HEAPSIZE];
allocated and blocks will be kept in sync. Specifically,
- For any two distinct, in-use blocks in
blocks, the address range[start, start+length)do not overlap. allocated[i]is true if and only if&heap[i]is within the range of some in-use block.
Your task
You will write two functions, called my_malloc and my_free that modifies our simulated "heap." To help guide your implementation, we have broken down the tasks into five (5) helper functions that you will implement. We have provided a copy of the skeleton below. You should familiarize yourself with it before you start implementing.
// typedef struct block {
// char *start;
// int length;
// int in_use;
// } block_t;
//
// char heap[HEAPSIZE];
// int allocated[HEAPSIZE];
// block_t blocks[NUMBLOCKS];
// TASK 1: Find a pointer to the block in `blocks` that is currently not marked "in-use."
// This should return the block at the minimum possible index.
// For example, if blocks 0, 1, 3, and 6 are in use, this should return `&blocks[2]`.
block_t *find_new_block() {
// TODO: implement!
// You may assume there will be at least one "block" available,
// thus the line of code below should not execute.
return NULL;
}
// TASK 2: Find a pointer `ptr` pointing to some subarea in `heap`, such that
// `heap[start..(start+size-1)]` is not in use.
// This should return the pointer at the minimum possible index.
// To check whether `heap[i]` is in use, see `allocated[i]`.
char *find_new_slot(int size) {
// int found_size = 0;
// int start = 0;
for (int i = 0; i < HEAPSIZE; ++i) {
// TODO: implement!
// return &heap[start];
}
// You may assume there will be at least one contiguous block with enough space available,
// thus the line of code below should not execute.
return NULL;
}
// TASK 3: Allocate a `size`-byte space and return the pointer to the start of the memory area.
// This should return the pointer at the minimum possible index.
char *my_malloc(int size) {
char *slot = find_new_slot(size);
block_t *block = find_new_block();
if (!slot || !block) // This should not execute
return NULL;
// TODO: set block information
// TODO: mark memory range allocated
// Hint: `slot` points to an address. How do you find what "index" this corresponds to in heap?
// Use pointer arithmetic! Then you can set allocated[index] = 1;
// return the start of the slot
return slot;
}
// TASK 4: Find a pointer to an in-use block where block.start == ptr.
// There should only be one such block.
block_t *find_matching_block(char *ptr) {
// TODO: implement!
// This line should not execute.
return NULL;
}
// TASK 5: Implement `my_free`!
void my_free(char *ptr) {
block_t *block = find_matching_block(ptr);
// TODO: mark the block unused (you do not have to clear other fields)
// TODO: mark the corresponding memory range unallocated
}
find_new_block
find_new_slot
my_malloc
find_matching_block
my_free