i had asked help on this question here Static member reclaiming memory and recovering from an exception
the program below is to allocate memory using own new operator. I have to throw exception on 5th object allocation and recover by freeing up memory (strange question i know, but it is assignment)
i have written the code here. allocation works, but when i try to call delete (through option ‘2’) i get stuck in infinite loop.
#include <iostream>
#include <cstdlib>
using namespace std;
class object
{
int data;
static int count;
static void* allocatedObjects[5];
public:
object() { }
void* operator new(size_t);
void operator delete(void *);
void static release();
void static printCount()
{
cout << count << '\n';
}
~object()
{
release();
}
};
int object::count = 0;
void* object::allocatedObjects[5];
void* object::operator new(size_t size)
{
if (count > 5)
throw "Cannot allocate more than 5 objects!\n";
void *p = malloc(size);
allocatedObjects[count] = p;
count++;
return p;
}
void object::operator delete(void *p)
{
free(p);
count--;
}
void object::release()
{
while (count > 0)
{
delete static_cast<object*> (allocatedObjects[count]);
}
}
int main()
{
object *o[10];
int i = -1;
char c = 1;
while (c != '3')
{
cout << "Number of objects currently allocated : ";
object::printCount();
cout << "1. Allocate memory for object.\n";
cout << "2. Deallocate memory of last object.\n";
cout << "3. Exit.\n";
cin >> c;
if (c == '1')
{
try
{
i++;
o[i] = new object;
}
catch (char* e)
{
cout <<e;
object::release();
i = 0;
}
}
else if (c == '2' && i >= 0)
{
delete o[i];
i--;
}
}
return 0;
}
What am i doing wrong?
EDIT
I have fixed the delete problem. By getting rid of destructor. And explicitly calling release at end of main.
But now my catch block is not catching exception. After allocating 5 objects exception is thrown (as traced through debugger) but not caught. New Changes in the code do not affect the related code.
The infinite loop occurs because the destructor (
~object()) is called beforeobject::operator delete(). Your destructor is attempting to delete the most recent object allocated, which calls the destructor on the same object. Theoperator delete()is never being called.I’m not sure what the
allocatedObjectsachieves here and the code will work without it. Get rid of therelease ()as well.UPDATE
OK, so there’s a need for the release (exception handling).
Don’t call release from the destructor. Instead, make the
operator delete()function set theallocatedObjectsentry to 0, after the callingfree(mirroring theoperator new()). Therelease()function is only called during exception handling and makes sure un-freed memory is freed correctly (i.e. loop throughallocatedObjectsarray andfreenon-zero entries and then setting them to zero.