c++ - Deleting an array of Class Objects -
i having problems memory leaks , can't seem find way patch them. characters class data member of type sprite*. sprite class inherited class image2d. , objects array of image2d objects holds possible sprites choose from.
class sprite : public image2d { private: char * name; int left, top; } sprite::~sprite() { delete[] name; } class image2d { private: consolecolor fg, bg; char *text; unsigned short width, height; } image2d::~image2d() { delete[] text; } class game { private: sprite* characters; } image2d * objects = new image2d[size]; //fill objects reading file. characters = new sprite[2]; int choice1, choice2; cout << "\n\nwhich sprite be? (1, 2, or 3) "; cin >> choice1; characters[0] = *(new sprite(objects[choice1].getfg(), objects[choice1].getbg(), objects[choice1].gettext(), "player", 10, 10)); cout << "\n\nwhich sprite opponet be? (1, 2, or 3) "; cin.clear(); cin.ignore(int_max, '\n'); cin >> choice2; characters[1] = *(new sprite(objects[choice2].getfg(), objects[choice2].getbg(), objects[choice2].gettext(), "computer", 70, 10)); delete[] objects; here destructor game class...
~game() { delete[] characters; } the leaks coming characters , when assign characters[0] , characters[1] i'm unsure how patch them.
solution: change...
characters[0] = *(new sprite(objects[choice1].getfg(), objects[choice1].getbg(), objects[choice1].gettext(), "player", 10, 10)); to
characters[0] = sprite(objects[choice1].getfg(), objects[choice1].getbg(), objects[choice1].gettext(), "player", 10, 10); and same characters[1].
well, here's 1 reason:
characters = new sprite[2] allocates 2 sprite instances using default constructor.
however, overwrite instances in:
characters[0] = *(new sprite(objects[choice1].getfg(), objects[choice1].getbg(), objects[choice1].gettext(), "player", 10, 10)); what doing shallow copy of data in sprite, meaning pointer name string being re-assigned point location in newly allocated object, original never freed. when call delete[], stuff allocated manually indeed freed, original default allocations not.
you should make it:
characters = *sprite[2] and:
characters[0] = new sprite(objects[choice1].getfg(), objects[choice1].getbg(), objects[choice1].gettext(), "player", 10, 10); or inside copy-constructor/operator= in sprite need make sure free held memory before re-assigning name/text pointers.
oh, , never looks free image2d array allocation did, , having same leak array well.
Comments
Post a Comment