NOTE: THIS IS NOT HOMEWORK IT IS FROM A PRACTICE EXAM GIVEN TO US BY OUR PROFESSORS TO HELP US PREPARE FOR OUR EXAM
I’m currently studying for a programming exam. On one of the sample tests they gave us we have the following question:
Suppose you have been given a templated Container that holds an unordered collection of objects.
template <typename T>
class Container {
public:
void insert(T *op);
// EFFECTS: inserts the object pointed to by op into
// the container
T *remove();
// EFFECTS: removes an object from the Container, and
// returns a pointer to it. Returns NULL if no
// objects remain in the Container.
// Note: the implementation can choose which
// object to return if more than one exists.
Container(); // ctor
Container(const Container &l); // copy ctor
Container &operator=(const Container &l); // assignment
~Container(); // dtor
private:
...
};
Note that this is the interface only; the implementation details have been left out for brevity.
However, you may assume that the implementation is node based; a linked collection of nodes
hold objects.
You suspect that the implementation of the destructor does not satisfy the Conservation Rule of the At-Most-Once invariant, and is leaking memory instead. Write an acceptance test (similar to those in Project 4) to check for this condition. You must supply a suitable contained type, and a main that performs the test.
Note that you cannot depend on any behavior that the language leaves undefined, you may not
assume that you have the altnew allocator from Project 5 available to you, and you may not
override the delete operator. Hint: you are allowed to use a global variable.
I though something like:
#include <iostream>
using namespace std;
int *p = NULL;
void leak() {
int *num = new int(5);
p = num;
delete num;
}
int main() {
if ((*p = 6)) {
cout << "Memory leak\n";
} else {
cout << "No Leak\n";
}
}
The basic idea behind this is I though I couldn’t write to a space of memory that I hadn’t allocated. In compiling this test code though it works just fine so apparently you can. Any ideas on how to write such a test case though?
What if you create a class to use as the template parameter that will add 1 to a global variable in it’s constructor and decrease that same global variable by 1 in it’s destructor.
Then you can perform whatever tests you want on the container (create it, fill it and empty it, delete it, etc) and check for memory leaks by checking that the global variable is 0 after the container has been destroyed.