I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:
class MemoryObject {
private:
static std::list <MemoryObject *> alive, dead;
long references;
public:
MemoryObject() {
alive.push_back(this);
references = 0;
}
static void deepClean() {
clean();
std::list<MemoryObject *>::iterator iterator;
for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
MemoryObject *object = *iterator;
Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
"\nSize: %d",
alive.size());
delete object;
}
alive.clear();
}
void reference() {
references ++;
}
void release() {
references --;
if(references <= 0) {
dead.push_back(this);
alive.remove(this);
}
}
static void clean() {
std::list<MemoryObject *>::iterator iterator;
for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
delete(&iterator);
dead.clear();
}
~MemoryObject() {
clean();
}
};
std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;
Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)
) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...
Here's where I'm calling it from:
#include <stdlib.h>
#include <stdio.h>
#include "log/log.hpp"
#include "memory/object.hpp"
int main(int argc, char *argv[]) {
MemoryObject foo;
foo.release();
MemoryObject::deepClean();
return 0;
}
In your clean
function you have:
delete(&iterator);
That will compile, but will attempt to delete the iterator itself - which is on the stack (which will crash).
I suspect you wanted:
delete(*iterator);