I have written a program for a double-ended queue using an array in C++. One of the requirements of the assignment is to handle exceptions.
One of the exceptions we are supposed to check for is the out of memory exception.
Since it is a dynamically-sized queue I have a method that doubles the size of the array when it gets full. Like this:
try{
doubleArray();
} catch (bad_alloc& e) {
throw bad_alloc();
}
In the main file, this throw
s of bad_alloc
is caught.
I have no idea how to test if this works or not. I'm using a Mac with X-code and also use the Mac terminal to compile and test the files. Does anyone know how to test this exception? i.e. set memory limits or something in either of those platforms? Or even if I'm doing it right or not?
EDIT (more info):
This is my implementation of doubleArray
:
void Deque<T>:: doubleArray(){
int newSize = size_of_Deque * 2;
T *newElement = new T[newSize];
int temp = front;
int begin = (newSize/4);
front = begin;
int end = size_of_Deque + begin - 1;
while (begin<=end) {
newElement[begin] = element[temp];
begin++;
temp = (temp + 1)% size_of_Deque;
}
element = newElement;
back = end;
size_of_Deque = newSize;
delete [] newElement;
}
So when the new array (with the double the size of the original array) is allocated that's when there could be the potential for out of memory case. That's why I did:
try{
doubleArray();
}catch (bad_alloc& e) {
throw bad_alloc();
}
Again, my main issue is that I have no idea how to test to see if it works. Is there any way to set memory limits in the terminal or in X-code?
Create a test program that
doubleArray()
to increase the size to some number, say 65kb (how you will do this depends on the API of your data structure)std::bad_alloc
is thrownTo run the test program in a restricted memory environment
ulimit -m 64
. This limits the amount of memory available to the current user to 64 kb. The number depends on what you chose in step 2 above.