XercesDOMParser scoped instantiation causes segfault

204 Views Asked by At

I have just come across a strange behavior of the Xerces-C library which I do not understand. The following code, which has already been seen in loads of examples, works for me:

#include <iostream>

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>

using namespace std;
using namespace xercesc;

int main (int argc, char* argv[])
{
    try {
        XMLPlatformUtils::Initialize ();
        XercesDOMParser* parser = new XercesDOMParser ();
        // here one might want to add some useful operations
        delete parser;
        XMLPlatformUtils::Terminate ();
    }
    catch (...) {
        cout << "caught some exception" << endl;
    }

    return 0;
}

Surely, this code does not do many meaningful things. But it runs and in particular terminates cleanly.

Now, I was trying to avoid the new/delete and switch to a scoped object, like so:

#include <iostream>

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>

using namespace std;
using namespace xercesc;


int main (int argc, char* argv[])
{
    try {
        XMLPlatformUtils::Initialize ();
        XercesDOMParser parser;
        // here one might want to add some useful operations
        XMLPlatformUtils::Terminate ();
    }
    catch (XMLException& exc) {
        cout << "caught an XMLException" << endl;
    }
    catch (...) {
        cout << "caught an exception" << endl;
    }

    return 0;
}

This or similar code has also been seen many times. However, when I run it, it creates a segfault after (?) XMLPlatformUtils::Terminate() (that's at least, what my debugger is suggesting). Still, I have successfully worked with a parser object created in that way. And if I omit the call to Terminate(), I see my process terminate cleanly.

Does anyone have a clue what I am doing wrong here?

1

There are 1 best solutions below

0
Midi On

Paul's comment already gave the correct answer and his explanation why does make sense. So for completeness, here is the code that actually works (note the explicitly created inner scope):

#include <iostream>

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>

using namespace std;
using namespace xercesc;


int main (int argc, char* argv[])
{
    try {
        XMLPlatformUtils::Initialize ();
        {
            XercesDOMParser parser;
            // here one might want to add some useful operations
        }
        XMLPlatformUtils::Terminate ();
    }
    catch (XMLException& exc) {
        cout << "caught an XMLException" << endl;
    }
    catch (...) {
        cout << "caught an exception" << endl;
    }

    return 0;
}

Thank you Paul!