Due: Wednesday, July 31st, 2024 by 10:00 am; No late
exercises accepted.
Goals: Learn how to use C++ smart pointers to handle
resource management, particularly heap memory.
Description: Consider the following C++ file, named ex14.cc: (right-click the link to download)
/* * Copyright ©2024 Alex Sanchez-Stern. All rights reserved. Permission is * hereby granted to students registered for University of Washington * CSE 333 for use solely during Summer Quarter 2024 for purposes of * the course. No other use, copying, distribution, or modification * is permitted without prior written consent. Copyrights for * third-party components of this work must be honored. Instructors * interested in reusing these course materials should contact the * author. */ #include <algorithm> #include <cstdlib> #include <iostream> #include <vector> int main(int argc, char **argv) { // Allocate an integer on the heap, initialize to value 5. int *x = new int(5); std::cout << "*x is: " << *x << std::endl; // Allocate a vector of integers on the heap, add some values to // that vector, sort the vector, print the values. std::vector<int> *v = new std::vector<int>; v->push_back(13); v->push_back(42); v->push_back(17); std::sort(v->begin(), v->end()); std::cout << "sorted v: "; for (int &el : *v) { std::cout << el << " "; } std::cout << std::endl; // Allocate a vector of (integer pointers) on the stack, add some // values to the vector from the heap, print the values. std::vector<int*> v2; v2.push_back(new int(13)); v2.push_back(new int(42)); v2.push_back(new int(17)); std::cout << "unsorted v2: "; for (int *el : v2) { std::cout << *el << " "; } std::cout << std::endl; return EXIT_SUCCESS; }
If you try compiling and running this program under valgrind,
you'll notice that there are several memory leaks in it, all
arising from allocating values on the heap using new
but not
deallocating them. Your challenge is to fix these memory leaks.
However, to make it interesting, you are not allowed to directly use
delete
(or free
, which would be a mistake, of course).
Instead, you have to modify the code to use the std::unique_ptr
smart pointer. So, for example, line 19 of the program
allocates an integer on the heap using new
. You will need to
modify that line to transfer ownership of the allocated integer
to a std::unique_ptr<int>
.
The only modifications you are allowed to make to the code are
those involved with adding in the appropriate std::unique_ptr
support. When finished with your modifications, your code must
compile without errors or warnings, and have no crashes, memory
leaks, or memory errors on the CSE Linux machines.
You should compile your code with:
g++ -Wall -g -std=c++17 -o ex14 ex14.cc
Modify the comment at the top of your ex14.cc file with your name and CSE or UW email address, and submit your exercise using the Gradescope dropbox linked on the course resources web page.