Reputation:
In this loop I call toString()
method on svg tag's childs. But every time I get Segmentation fault in the first iteration.
std::list<Tag*> children;
std::string TagSvg::toString() const{
if(this->getChildren().empty()) return "<svg/>";
std::string temp="";
temp+="<svg>\n";
for(std::list<Tag*>::const_iterator it=this->getChildren().begin(); it != this->getChildren().end(); ++it){
temp+=(*it)->toString();
}
temp+="</svg>\n";
return temp;
}
std::list<Tag*> Tag::getChildren() const{
return children;
}
As you can see in this image, SVG Tag has childs, it should call toString()
on TagG in first iteration, but it doesn't even set iterator correctly as you can see, because TagG has 2 childs and that dereferenced iterator has 0 childs and weird attributes. Could someone show me what I got wrong? Thanks!
Upvotes: 0
Views: 84
Reputation: 29724
probably your function getChildren
returns by value and then
std::list<Tag*>::const_iterator it=this->getChildren().begin();
and
it != this->getChildren().end();
points to the begin and the end of different containers. From your edit it is clear this is exactly this case, so please do a change:
std::list<Tag*>& Tag::getChildren() const{
return children;
}
or do it like:
std::list<Tag*> children = this->getChildren(); //now you ensure you work on
//a single and the same container
for(std::list<Tag*>::const_iterator it=children.begin();
it != this->children.end(); ++it){
temp+=(*it)->toString();
}
Upvotes: 2