My code looks something like this:
xmlparser.h file:
#include <libxml++/libxml++.h>
#include <iostream>
using namspace std, xmlpp;
class xmlpar {
public:
xmlparse(){}
~xmlparse(){}
const Node* root_node();
};
xmlparser.cc file:
#include "xmlparser.h"
const Node* xmlpar::root_node() {
const Node* rnode;
DomParser parser;
parser.parse_file("sample.xml");
if (parser) {
rnode = parser.get->document()->get_root_node();
cout << rnode->get_name(); // prints "component" as in xml file
return rnode;
}
}
My main.cc file:
#include "xmlparser.h"
int main() {
xmlparser par;
const Node* root = par.root_node();
cout << root->get_name(); // prints "PQ". --> Problem location
}
I first compiled the xmlparser.cc file, then the main.cc, and then created an executable with both main.o and xmlparser.o . I’m not getting any error during compilation but Like in the code if I’m returning rnode from the method root_node(), the values of the root
gets changed to something like “PQ” instead of “component”. Can anyone please tell me what’s happening here and the solution to the same.
I don’t know
libxml2, but it seems like you return pointer to a local object.in
const Node* xmlpar::root_node()is a local object. Then you do what you do and finallywhich makes
rnodeto point to some place in the document. You return pointer to it, but after the end of the function (after it returns), theparseris destroyed, as it’s local object.This makes the returned pointer invalid and you have undefined behavior