Project 2: Build Your Own Vec
Welcome to your second project!
We have been using Vec throughout our time with Rust, and lists in almost every Python program before that. You can push things onto the end and the list grows. But memory doesn't grow. When a program asks for a block of memory it gets exactly that much, and the block can never get bigger. So how does a Vec hold a million elements when it started out holding none?
In this project you will build your own Vec, twice. First a slow version that is safe and simple, then a fast one that manages its own memory by hand with raw pointers. Then you will race them and explain what you see.
This project runs alongside the memory unit in lecture: the stack, the heap, pointers, ownership, and borrowing. You will ask for memory, put values into it, move them around, and give the memory back, and when you get one of those wrong you will see exactly what Rust's rules have been protecting you from.
You will also practice a new git workflow: each checkpoint lives on its own branch, which you merge into main with a pull request when it is done. In checkpoint 3 you will use branches for something else they are good for, which is trying out ideas without committing to them.
What is due when
- Checkpoint 1, Friday October 16.
SlowVec - Checkpoint 2, Friday October 23.
FastVec'sgetandpush, and how it grows - The project, Friday October 30.
remove,clear,Drop, the benchmark, and the writeup - Code review, in discussion the week of November 2.
Checkpoint 1 is short on purpose, since it falls the week after the midterm. Checkpoint 2 is the hardest part of the project, so leave yourself time for it.
Meet your project repo
Your starting point is https://github.com/rust4ds/ds210-fa26-project-2.
Same as Project 1: on GitHub, click Use this template, then Create a new repository. Name it ds210-fa26-project-2 and set it to Private. Then clone it.
This time the whole project arrives at once. There is no update to merge partway through.
slow_vec/ Part 1
src/lib.rs SlowVec. Your push and remove go here
src/playground.rs a scratch pad for trying SlowVec out
src/memory.rs watches what gets dropped, and when
tests/cp1.rs the checkpoint 1 tests
fast_vec/ Part 2
src/lib.rs FastVec. Your get, push, remove, the clear fix and Drop go here
src/growth.rs how a FastVec picks its new size. Yours
src/timing.rs timing pushes, for the benchmark. Yours
src/benchmark.rs runs the benchmark and draws the plots. You choose what it compares
src/playground.rs a scratch pad for trying FastVec, MALLOC and pointers out
src/memory.rs watches what gets dropped and freed, and when
tests/cp2.rs the checkpoint 2 tests
tests/cp3.rs the checkpoint 3 tests
fixed/ FixedSizeArray, which SlowVec is built on
malloc/ the memory allocator FastVec uses
tracker/ wraps values so you can see when they are dropped
README.md instructions to start, and where your writeup goes
You will only edit files in slow_vec/ and fast_vec/. The other three folders are tools we built for you. You are welcome to read them, but shouldn't edit them.
Everywhere you have to write code is marked todo!, and the program stops if it reaches one. Only change what this page asks you to: the functions marked todo!, the Drop for FastVec, your choices in benchmark.rs, and the writeup in README.md.
Working on branches
In Project 1 you may have committed straight to main. This time, each checkpoint's work happens on its own branch, and only reaches main through a pull request once it works.
Start checkpoint 1 like this, from inside your repo:
git switch -c checkpoint-1
switch -c makes a new branch and moves you onto it (git checkout -b checkpoint-1 also works for this). Commit as you go, the same as always. The first time you push the branch, tell git where it goes:
git push -u origin checkpoint-1
After that, plain git push works.
When the checkpoint's tests pass, merge it into main with a pull request:
- On your repo's GitHub page, open the Pull requests tab and click New pull request
- Set base to
mainand compare tocheckpoint-1. GitHub shows you every change the merge would bring in. Read it over - Click Create pull request, give it a title, then Merge pull request
Then bring the merged main back to your laptop, and start the next checkpoint's branch from it:
git switch main # or git checkout main
git pull
git switch -c checkpoint-2 # or git checkout -b checkpoint-2
Gradescope will just grade the branch you point it to (which should be main), so you'll need to merge your pull request before submitting on Gradescope.
We will look at your branches and pull requests at code review, using git log --graph --all --oneline. Try that command yourself now and then. It draws your branches as lines, and it's a great way to see what git thinks is going on.
Running your project
Everything runs from the top folder of your repo:
cargo run --bin slow_playground # try out SlowVec and FixedSizeArray
cargo run --bin slow_memory # watch what SlowVec drops, and when
cargo run --bin fast_playground # try out FastVec, MALLOC, and raw pointers
cargo run --bin fast_memory # watch what FastVec drops and frees, and when
cargo run --release --bin benchmark # time your vectors and draw the plots
The playgrounds are yours to edit, and aren't graded. You can use them to try things out and see how they work.
Open that same top folder in VS Code, with code . from inside it, so that rust-analyzer sees the whole workspace and gives you types and errors as you type. If you open the folder above it instead, there is no Cargo.toml to find and you get no hints. If the status bar says rust-analyzer could not find a project, the reload steps are in Discussion 1.
Running the tests
cargo test --test cp1 # SlowVec
cargo test --test cp2 # FastVec's get and push, and growth
cargo test --test cp3 # remove, clear, Drop, and timing
cargo test # all the project's tests
Add part of a test's name to run only the tests that match it: cargo test --test cp2 memory, or cargo test --test cp2 growth.
When you first clone your repo, almost every test fails and you'll see a lot of warnings. Like in the last project, that's expected until you start writing your code.
If a test run stops partway with SIGSEGV, SIGBUS, SIGABRT, or some other signal, one of your unsafe blocks has corrupted memory, and it took the whole run down with it. That only becomes possible in checkpoint 2. The last test named before the crash is where to start, so run it on its own.
Things you will see before we teach them
<T>. SlowVec<T> and FastVec<T> work for any type of element: SlowVec<i32>, SlowVec<String>, SlowVec<bool>. The T stands for "whichever type the vector holds". You've seen them before in things like Vec<T>, Option<T>, and Result<T, E>. This is called a generic, and we cover generics properly in November.
impl Display for SlowVec<T> and impl Drop for FastVec<T>. These are traits, also a November topic. Display is what lets println!("{}", v) print a vector, and it is written for you. You will write the body of a Drop yourself in checkpoint 3, and this page gives you the outline. You can work with them just like implementing methods on enums and structs with impl.
Submitting
As with Project 1, each checkpoint and the final project will have its own Gradescope assignment, which asks you to log into GitHub and point it at your repo. Pick the main branch. Merge your pull request and push before you submit, because Gradescope reads GitHub, not your laptop.
Checkpoint 1: SlowVec
Our first vector is the simplest one that could possibly work. It is slow, and in checkpoint 3 you will measure exactly how slow, but it is safe, short, and it sets up everything that comes after.
What you are given: FixedSizeArray
SlowVec is built on a type we wrote for you, FixedSizeArray. It is a row of slots, and it can never change size. You decide how many slots when you make one, and that is how many it has forever.
It has five functions:
FixedSizeArray::allocate(n)makes a new array with exactlynempty slots.put(element, i)storeselementin sloti.get(i)returns a reference to the element in sloti, written&T.move_out(i)takes the element out of slotiand gives it to you, writtenT. The slot is empty afterwards.len()tells you how many slots it has
The difference between get and move_out matters a lot. Think of a reference as a read-only view of the element: get lets you look, and the element stays where it is, so you can get the same slot as many times as you like. move_out hands you the element itself, and the array no longer has it. You can only move_out a slot once, until something is put back in it.
Try it. Open slow_vec/src/playground.rs and run it:
cargo run --bin slow_playground
The program prints some output, then crashes, because push and remove are not written yet. Look at fixed_sized_array() first. It calls get twice and move_out once. Uncomment the second move_out and run it again. What happens? What if you get a slot after you move_out of it?
What you are writing
Open slow_vec/src/lib.rs. SlowVec is a struct with one field, fixed, which is the FixedSizeArray holding its elements. Most of its methods are written for you: new, len, get, clear, and two for converting to and from a regular Vec, which the tests use.
Every method takes some form of self first. Like with structs, it refers to the particular SlowVec the method was called on, so in my_vec.push(5), self is my_vec and self.fixed is my_vec's array.
Your job is to write two methods, push and remove.
Here is the problem with both of them. self.fixed cannot change size. So you cannot add a slot to it for push, or take one away for remove. What you can do is make a new array of the right size, move every element across into it, and replace the old one:
// 1. Make a new FixedSizeArray. One slot bigger for push, one smaller for remove.
// Which method on SlowVec tells you the current length?
let mut tmp = /* create a FixedSizeArray of the right size */
// 2. Move every element out of self.fixed and into tmp.
// For push, put the new element in the end.
// For remove, skip the element that's removed and close up the gap.
// 3. Replace the old array with the new one.
self.fixed = tmp;
When the last line runs, the old array is thrown away and its memory goes back to the computer. You don't have to do anything to make that happen. Hold that thought until checkpoint 3.
Run slow_playground again when you think you're done. In slow_vec_push() and slow_vec_remove(), the comment next to each println! says what it should print.
Then run slow_memory, which uses our Tracker to watch your elements and reports any that are never cleaned up. Yours will all be cleaned up, and it is not because you were careful: safe Rust does not let you lose track of them. In part 2 that guarantee goes away, and this tool will be how you find your mistakes.
Checklist
- Make your own private copy of the Project 2 repository with Use this template, then clone it
-
Put your name on the Author line of
README.md -
Make a
checkpoint-1branch -
pushworks -
removeworks -
cargo test --test cp1is entirely green, twelve tests -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Read the
memorytests incp1.rs. They watch every allocation and free, so they check thatpushmakes exactly one new array of the right size, and that the old one is given back. If one fails, the transcript of allocations in its message says what you did instead - For
pushandremovetry writing out what the arrays look like before and after for a small case before coding them up - Consider whether you need to use
get,move_out, neither, or both in your methods - If your tests suddenly won't compile, check the playgrounds too!
Checkpoint 2: FastVec
SlowVec copies the entire vector on every single push. If you push a million elements to an array by looping over them, the array gets copied and moved 999,999 times. Rust's Vec and Python's lists don't work that way, and our FastVec won't either.
Making it fast takes two ideas: leaving room to grow, and managing the memory yourself.
Idea 1: length and capacity
SlowVec only ever has exactly as many slots as it has elements. FastVec keeps track of two numbers instead:
- its length: how many elements it holds right now
- its capacity: how many it has room for before it has to grow
When the length is less than the capacity, a push is cheap: put the element in the next empty slot, and you're done. Only when the vector is full does it have to grow, by allocating a bigger block, moving everything across, and freeing the old one, just like SlowVec.
The trick is in how much bigger. SlowVec grows by one, so it is full again immediately. If FastVec doubles its capacity every time it grows, the resizes get further and further apart.
Here is what happens when you push 8 elements into a new FastVec, which starts with capacity 1. Count one step for every element written or moved:
| Push | Before: length, capacity | What happens | Steps | After: length, capacity |
|---|---|---|---|---|
| 1 | 0, 1 | room, just write it | 1 | 1, 1 |
| 2 | 1, 1 | full, grow to 2: move 1, write 1 | 2 | 2, 2 |
| 3 | 2, 2 | full, grow to 4: move 2, write 1 | 3 | 3, 4 |
| 4 | 3, 4 | room | 1 | 4, 4 |
| 5 | 4, 4 | full, grow to 8: move 4, write 1 | 5 | 5, 8 |
| 6 | 5, 8 | room | 1 | 6, 8 |
| 7 | 6, 8 | room | 1 | 7, 8 |
| 8 | 7, 8 | room | 1 | 8, 8 |
That is 15 steps for 8 elements, under 2 per push. SlowVec would have taken 1 + 2 + ... + 8 = 36. The gap gets wider the more you push, and in the writeup you will explain why.
Idea 2: managing memory yourself
FastVec does not use FixedSizeArray. Instead it asks for raw memory, and keeps track of what is in it on its own. The struct for FastVec holds a pointer to the start of its memory, plus the length and capacity:
pub struct FastVec<T> {
ptr_to_data: *mut T,
len: usize,
capacity: usize,
growth: Growth,
}
*mut T is a raw pointer: an address in memory, where Rust trusts you that a T lives. You met these in lecture on October 16.
Here is a FastVec holding five numbers, drawn the way we draw a Vec in lecture:
Stack: Heap (from MALLOC):
┌───────────────────────┐ ┌────┬────┬────┬────┬────┬────┬────┬────┐
│ v: FastVec<i32> │ │ 10 │ 20 │ 30 │ 40 │ 50 │ ?? │ ?? │ ?? │
│ ├ ptr_to_data ────────┼──────────▶│ │ │ │ │ │ │ │ │
│ ├ len: 5 │ └────┴────┴────┴────┴────┴────┴────┴────┘
│ ├ capacity: 8 │ slots 0 to 4 hold a value, 5 to 7 hold garbage
│ └ growth: Double │
└───────────────────────┘
len says how many slots hold a value, counting from the beginning. capacity says how many slots the block of memory has. Nothing in memory itself marks the boundary between them. Slot 5 looks exactly like slot 4 to the computer; only len keeps track of which slots are real. Keeping len correct is core to this part of the project.
Asking for memory. We give you an allocator called MALLOC, which works like C's malloc and free from the October 19 lecture. It has two functions:
// Give me this many bytes. Returns a pointer to the first one.
unsafe fn malloc(bytes: usize) -> *mut u8
// Give back memory that malloc gave you. Pass the exact pointer malloc returned,
// and the whole block is freed.
unsafe fn free(ptr: *mut u8)
The only difference from C's malloc is that ours also writes down every allocation and free in a log, which the tests read to check your work.
malloc counts in bytes, and hands back a pointer to bytes, *mut u8. You want room for some number of Ts, so ask for the right number of bytes and then tell Rust what will live there, with as:
// Room for exactly one i32
let one: *mut i32 = unsafe { MALLOC.malloc(size_of::<i32>()) as *mut i32 };
// Room for n elements of type T, whatever T is
let many: *mut T = unsafe { MALLOC.malloc(size_of::<T>() * n) as *mut T };
// Finished with it
unsafe { MALLOC.free(many as *mut u8) };
size_of::<T>() is how many bytes one T takes. Never hard-code a size, since T could be anything.
Using the memory. There are three things you can do through a pointer, and the focus of checkpoints 2 and 3 is on these:
ptr::write(p, value)putsvalueatp. It overwrites whatever bytes were there without looking at themptr::read(p)moves the value atpout and hands it to you. Afterwards, treat that slot as empty&*pgives you a reference to the value atp, without moving it. The value stays where it is
Notice that 2 and 3 are basically move_out and get from checkpoint 1. The difference is that FixedSizeArray checked you were using them correctly, and nothing checks you now. These are the rules you have to keep yourself:
- Never read from a slot before you have written to it. Memory from
mallocholds whatever was there before, which is garbage - Never read from a slot twice without writing to it in between. After
ptr::read, the value belongs to whoever you handed it to. Reading it again makes a second copy of something there should only be one of, and both copies will try to clean up after themselves - Never write over a slot that still holds a value.
ptr::writedoes not clean up the old value first, so it is lost and never cleaned up
To get at slot i instead of the first slot, use p.add(i). It hands you a new pointer i elements further on, counting in elements and not bytes, since Rust knows how big a T is. It changes nothing in memory and does not change p. It is arithmetic on an address, the way i + 2 is arithmetic on a number, so you use the result right where you need it:
let p: *mut i32 = unsafe { MALLOC.malloc(size_of::<i32>() * 10) as *mut i32 };
unsafe {
// Write 33 into slot 2, the third element
ptr::write(p.add(2), 33);
// Look at it without moving it. You can do this as often as you like
let r: &i32 = &*p.add(2);
println!("{}", r); // 33
// Move it out. Slot 2 is empty again now
let v: i32 = ptr::read(p.add(2));
println!("{}", v); // 33
// What do you think this does? Slot 10 does not exist
// println!("{}", &*p.add(10));
MALLOC.free(p as *mut u8);
}
Every one of these operations is unsafe. That word does not switch Rust's rules off. It means you are signing your name to them: Rust cannot check this code, so you are promising that you did.
Open fast_vec/src/playground.rs and run it before you write anything:
cargo run --bin fast_playground
malloc_and_ptr() is a working example of all of this, and it prints the addresses it gets. The comments at the end ask what happens if you go past the end of a block, or read before writing. Try them!
What you are writing
Three things, in two files. The checkpoint 2 tests are in fast_vec/tests/cp2.rs.
1. next_capacity, in src/growth.rs. Doubling is not the only way to grow. Growth is an enum with three strategies:
Growth::Double: twice the old capacityGrowth::Multiply(factor): the old capacity timesfactor, rounded down. SoMultiply(1.5)grows by halfGrowth::Add(slots): the old capacity plus a fixed number of slots
next_capacity takes the current capacity and returns the new one. match on self to decide which rule applies. One requirement holds for every strategy: the answer must always be bigger than the capacity you were given, or push has nowhere to put the new element. Read that requirement carefully, and think about whether every strategy meets it for every capacity.
FastVec::new() uses Double. FastVec::with_growth(...) lets you pick, which you will need in checkpoint 3.
2. get, in src/lib.rs. Return a reference to the element at index i, using .add(i) and &*. You want to look at the element, not move it out, so that the caller can get it again later.
Before that, check the index. If i is not less than the length, there is no element there to return: the slot is either garbage or does not exist. Panic instead, with exactly this message:
panic!("FastVec: get out of bounds");
3. push, in src/lib.rs. Two cases, already set up for you in the stencil:
- There is room (length less than capacity). Write the element into the next empty slot, and update the length
- The vector is full. Ask
self.growthfor the new capacity. Allocate that much memory. Move every element from the old memory to the new, withptr::readfrom the old andptr::writeinto the new. Free the old memory. Then pointself.ptr_to_dataat the new memory, and update the capacity. Now there is room, so carry on as in the first case
Checklist
-
Merge checkpoint 1, pull
main, and make acheckpoint-2branch from it -
next_capacityworks for all three strategies.cargo test --test cp2 growth -
getworks, and panics out of bounds.cargo test --test cp2 get -
pushworks.cargo test --test cp2 push -
cargo test --test cp2is entirely green, seventeen tests -
cargo test --test cp1is still green -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Write
getfirst. Almost every other test uses it to check its answer, and so does printing aFastVecwithprintln! - Draw it. Boxes for slots, an arrow for the pointer, and a mark for which slots hold a value. Most bugs in this part of the project occur when a slot holds a value when you think it is empty, or the other way around
- When a test crashes instead of failing, the compiler cannot help you! Inside
unsafebugs happen that the compiler usually catches. To debug, rerun that one test by name instead of all at once. Printlen,capacity, andptr_to_data(with{:p}) before and after the step you suspect. Then check the three slot rules one at a time against your drawing. A crash inpushis often agetor a loop bound that is off by one somewhere earlier push_allocates_then_frees_the_oldchecks the order of what you do, by readingMALLOC's log. Allocate the new block before freeing the old one: you need both at once, to move from one to the other- Run
fast_memoryas you go. Case 1 pushes and removes; it will crash onremoveuntil checkpoint 3, so read what it printed up to that point - Copying the elements across one at a time is right. There are faster ways, but they are not the point here
- If your tests suddenly won't compile, check the playgrounds too!
Checkpoint 3: remove, clean up, and measure
FastVec can grow now. In this checkpoint you finish it, by teaching it to shrink and to clean up after itself, and then you find out whether all that work was worth it.
What you are writing
The tests are in fast_vec/tests/cp3.rs.
1. remove, in src/lib.rs. Remove the element at index i, and shift every element after it down one slot to close the gap. Unlike SlowVec, this needs no new memory: a FastVec holding [1, 3, 5, empty] becomes [1, 5, empty, empty], with the same capacity and one fewer element.
The removed element has to be cleaned up, so move it out with ptr::read first. Then, for every slot j after i, read its element out and write it into slot j - 1.
If i is not less than the length, panic with exactly this message:
panic!("FastVec: remove out of bounds");
2. Fix the bug in clear. We wrote clear for you, and it has a bug. It frees FastVec's memory, and on its own that looks right. Run this to see what it misses:
cargo run --bin fast_memory
Look at case 2. The Tracker says three values were never cleaned up, even though the memory is freed. Freeing memory throws away the bytes inside the vec itself, but it does not clean up the values that were in them (if they're heap types). For an i32 that makes no difference, but a String owns some heap memory of its own, and only the String itself knows to give it back. So before you free the block, every element in it has to be moved out and dropped. Which of the three pointer operations moves a value out?
3. Drop for FastVec. What happens to a FastVec when it goes out of scope?
Right now, nothing at all. Its memory came from MALLOC, and Rust has no idea it is there, so it never gets freed, and neither do the elements in it. Every FastVec your program has ever made has leaked.
SlowVec never had this problem. The third ownership rule in Rust says that when the owner of a value goes out of scope, the value is dropped, and that is what happened to each old FixedSizeArray in checkpoint 1. Dropping one runs some code that FixedSizeArray provides, which cleans up its elements and frees its memory. FastVec needs that code too, and now you'll write it. It goes where the comment YOUR Drop GOES HERE is in src/lib.rs, and has this shape:
impl<T> Drop for FastVec<T> {
fn drop(&mut self) {
// Runs automatically when a FastVec goes out of scope.
// Clean up every element, then free the memory.
}
}
You never call drop yourself! Implementing Drop for FastVec means Rust will call it for you at the end of the vector's scope. There's a function you can call here that already does the work, so the body is one line of code.
4. The timing functions, in src/timing.rs. time_fast_pushes and time_slow_pushes each push n elements, one at a time, and every every pushes record a sample: how many elements have been pushed so far, and how many milliseconds have passed since the first push. The comment at the top of the file describes them exactly, and shows how to use Instant, Rust's stopwatch.
time_fast_pushes is given the FastVec to push into, so that the benchmark can hand it vectors with different growth strategies. Make sure you push into that one.
5. Your growth experiments, in src/benchmark.rs. Once the timing tests pass, run the benchmark:
cargo run --release --bin benchmark
Use --release. It turns on the compiler's optimizations. Without them the benchmark takes much longer, and the timings mostly measure how slow unoptimized code is.
It writes two plots into the top folder of your repo. benchmark_slow.png races SlowVec against FastVec. benchmark_growth.png races growth strategies against each other, and so far it has only one: Double. Which others go on it is up to you, and this is where branches come in again.
Each idea you try gets its own branch. For example, to try out a few multipliers:
git switch -c growth-multiply
Then add the strategies you want to compare at YOUR CHOICES GO HERE in benchmark.rs, up to four lines on the plot in total. Each one looks like the Double line above it, with a different Growth and name:
series.push(("Multiply(1.5)", time_fast_pushes(FastVec::with_growth(Growth::Multiply(1.5)), n, every)));
Run the benchmark, look at the plot, and commit benchmark.rs and both plots on that branch. Push it with git push -u origin growth-multiply.
Then go back and try something else on a new branch:
git switch checkpoint-3
git switch -c growth-add
This is the other thing branches are for. If an experiment goes wrong, you can commit it anyway and switch back to a working branch. git switch checkpoint-3 puts everything back the way it was, and the broken attempt is still sitting on its own branch if you ever want to revisit it.
Make at least two experiment branches, each with a name that starts with growth-. Different strategies, different knob settings, a mix: your call. Then pick the one whose plot makes the best argument, and merge it into your checkpoint branch:
git switch checkpoint-3
git merge growth-multiply # or whatever branch you want to keep
That brings its benchmark.rs and plots along with it. Both plots have to be committed on main when you submit: the writeup is about them, and a missing plot costs points. Leave the other experiment branches unmerged, but pushed. They stay on GitHub as a record of what you tried, and we will look at them with you at code review.
6. The writeup, in the README of your repo. The questions are at the end of this page, and the headings are already in your README. They ask about your own plots, so you cannot answer them until your benchmark runs.
Checklist
-
Merge checkpoint 2, pull
main, and make acheckpoint-3branch from it -
removeworks, and panics out of bounds.cargo test --test cp3 remove -
cleardrops every element.cargo test --test cp3 clear -
FastVechas aDrop.cargo test --test cp3 dropping -
The timing functions work.
cargo test --test cp3 timing -
cargo testis entirely green, all three checkpoints -
At least two
growth-branches, each with a plot committed, pushed to GitHub. We check these with you at code review -
One of them merged into
checkpoint-3, so both plots end up onmain - The writeup is answered in your README
-
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Read the
cp3tests before you start. Their names say what they check:remove_never_allocates_or_freesandremove_drops_exactly_one_element - In
remove, the last element's old slot is empty afterwards. Nothing should read it again, and nothing will, as long as you update the length Dropruns on everyFastVec, including one that was already emptied byclearorinto_vec. Both of those leave the pointer null and the capacity at zero. Remember, freeing the same block twice is an issue- If a timing test says the times went down, you are probably restarting the stopwatch inside your loop
- If the benchmark seems to hang, check you used
--release.SlowVecgets slow fast, and debug mode makes it many times slower - A plot with one line that dwarfs the others hides the differences between the rest. If two strategies look identical, try putting them on a branch of their own or make them more distinct from each other
- If your tests suddenly won't compile, check the playgrounds too!
The writeup
Your writeup goes in the README of your repo, under the headings that are already there. Leave the rest of that file alone.
Two to three sentences per question, unless it says otherwise.
Reading the plots
1. SlowVec against FastVec. Look at benchmark_slow.png. Describe the shape of each curve. Why does SlowVec's bend upward? Write the total cost of n SlowVec pushes as a function of n. Hint: how many elements does the k-th push move?
2. Why push is fast on average. Some FastVec pushes copy the entire vector, and yet Double's curve is a straight line. Count the steps for 16 pushes, the way the table in checkpoint 2 does for 8. Then explain, in terms of how often resizes happen and how big they are, why the average cost per push stays the same however big n gets.
3. Your growth experiments. Which strategies and settings did you try, and on which branches? What did the plots show? Which branch did you merge, and why that one? Being fastest is not the only thing that matters: right after a resize, how much of each strategy's memory is empty?
4. Why Add eventually loses. Pick any fixed k. As n grows, Add(k) eventually loses to Double, even though a big enough k can win at one particular n. Why? What changes about the curve as k gets bigger, and what doesn't?
Memory
5. Two kinds of leak. The tests check for leaks in two ways: Tracker and MALLOC's log. What does each one catch that the other misses? Describe a Drop that would pass one check and fail the other.
6. The bug in clear. What was wrong, and how did you find it? Why could you not have written the same bug in SlowVec?
Process
7. What's something you tried that failed at first on this project, and how did you adapt?
Your AI citation. Who and what you used, and how. Course policy is in the syllabus.