0

I have this class:

// XmlWrapper.h
class XmlWrapper{
private:
    xml_document<> doc;
public:
    XmlWrapper();
    string addNode( string node_name);
            string getXmlString();
};

// XmlWrapper.cpp
XmlWrapper::XmlWrapper(){};

XmlWrapper::addNode(string node_name){
    char _name[name.size()+1];
    strcpy(_name,name.c_str());
    _name[name.size()] = '\0';
    xml_node<> *root = doc.allocate_node(node_element,_name);
    this->doc.append_node(root);
    delete root;
    return SUCCESS;
}

string XmlWrapper::getXmlString(){
    string xmlString;
    print(back_inserter(xmlString), this->doc, 0);
    return xmlString;
}

And this is my main.cpp:

XmlWrapper wrapper;
wrapper.addNode("message");
cout << wrapper.getXmlString() << endl;

However, my result is a list of weird thing!! if i cout wrapper.getXmlString() in addNode function, the result will be okie! So what's is my problem?

Edited: if i use directly in main.cpp like this below,every thing is go right:

xml_document<> doc;
xml_node<> *message_node = doc.allocate_node(node_element, "message");
doc.append_node(message_node);
string buffer;
print(back_inserter(buffer),doc,0);
cout << buffer << endl;

Why this thing happen?

Kingfisher Phuoc
  • 7,392
  • 8
  • 43
  • 75
  • You're not using `new` to allocate memory. Why do you have the `delete root;` statement then? Further, for the node names to stick, you should probably use `allocate_string`. Read the documentation. – dirkgently Jun 11 '12 at 10:13
  • I'm just worried about memory leak! Is this right? – Kingfisher Phuoc Jun 11 '12 at 13:47
  • 1
    Your original code which uses a variadic array `_name` will cause issues with a dangling pointer (when you go out of the function, `_name` will be destroyed and your XML document will point to a region of memory that has been destroyed. – dirkgently Jun 11 '12 at 13:53
  • So i must declare `_name` as a pointer? Is there another way to save the xml to doc type :-? – Kingfisher Phuoc Jun 11 '12 at 13:59
  • 1
    I'd suggest using the `allocate_string` as provided by the library. – dirkgently Jun 11 '12 at 14:20

1 Answers1

1

What dirkgently said - _name is on the stack, and will be destroyed when you get out of the scope of the function. You can use allocate_string, or write your own garbage collection.

ModdyFire
  • 618
  • 2
  • 9
  • 18
  • The easiest garbage collection will be just adding vector member to your XmlWrapper, and push_back the string in add_node() – ModdyFire Jun 12 '12 at 07:17