Question

For some reason I'm getting a strange heap corruption from the following class definition file, most likely in the "CreateFromNode" function. Can anyone help me with this? I'd really like to deal with this right now since I caught it, and not see it manifest itself later. Also, no outside forces are modifying any members of this class (or it's members).

#include "Object.h"

TmxMap::Object::Object():name(), position(), size(), gid(-1), visible(true),
properties(), image(), polygon(NULL), polyline(NULL), ellipse(false){}

TmxMap::Object::Object(rapidxml::xml_node<>* const& object_node):name(),
    position(), size(), gid(-1), visible(true), properties(), image(),
    polygon(NULL), polyline(NULL), ellipse(false){
CreateFromNode(object_node);
}

TmxMap::Object::Object(TmxMap::Object const& from):name(from.name),
    position(from.position), size(from.size), gid(from.gid),
    visible(from.visible), properties(from.properties),
    image(from.image), polygon(from.polygon), polyline(from.polyline),
    ellipse(from.ellipse){}

TmxMap::Object::~Object(){
DeleteObjects();
}

void TmxMap::Object::CreateFromNode(rapidxml::xml_node<>* const& object_node){
DeleteObjects();

rapidxml::xml_node<>* data_node = NULL;
rapidxml::xml_attribute<>* data_attrib = NULL;

if((data_attrib = object_node -> first_attribute("name")))
    name = data_attrib -> value();

if((data_attrib = object_node -> first_attribute("width")))
    size.x = std::strtol(data_attrib -> value(), NULL, 10);
if((data_attrib = object_node -> first_attribute("height")))
    size.y = std::strtol(data_attrib -> value(), NULL, 10);

position.Set(
        std::strtol(object_node -> first_attribute("x") -> value(), NULL, 10),
        std::strtol(object_node -> first_attribute("y") -> value(), NULL, 10)
);

if((data_node = object_node -> first_node("polygon")))
    polygon = new Polygon2D<int>(data_node);

if((data_node = object_node -> first_node("polyline")))
    polyline = new Polyline2D<int>(data_node);

ellipse = (object_node -> first_node("ellipse") != NULL);
}

void TmxMap::Object::DeleteObjects(){
if(polygon){delete polygon; polygon = NULL;}
if(polyline){delete polyline; polyline = NULL;}
}

void TmxMap::Object::Destroy(){
name.clear();
position.Set();
size.Set();
gid = 0;
visible = true;
properties.Destroy();
image.Destroy();
DeleteObjects();
ellipse = false;
   }
Was it helpful?

Solution

Your copy constructor copies the pointers polygon and polyline.
This will lead to them being deleted multiple times.

You should copy those objects instead of the pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top