Search code examples
c++xcodepointersexc-bad-accesstinyxml2

TinyXML2 EXC_BAD_ACCESS Im sure its a null ptr but no idea why


So I have been at this for days, and I have no idea why a BAD_ACCESS error is thrown. Sometimes it works, sometimes it doesn't.

void xmlParser::parseXML(string file){

tinyxml2::XMLDocument doc;
if(!doc.LoadFile(file.c_str()))
{
    cout << "ERROR: TINYXML2 FAILED TO LOAD" << endl;
}
//XML FILE LAYOUT:
//<item>
//    <type id="laserWeapon" name="Laser Rifle">
//    <tooltip>
//    <stats>
//</item>

//error seems to occur on this line
tinyxml2::XMLElement* elementType = doc.FirstChildElement("item")->FirstChildElement("type");

string id = elementType->Attribute("id");
string name = elementType->Attribute("name");
cout << "id: " << id << endl;
cout << "name: " << name << endl;
}   

I use xmlparser.parseXML(xmlparser.path+"laserRifle.xml"); to load the file. Should I be parsing this as a string, or is there some null ptr I'm neglecting? I've tried to do an 'if nullptr' clause, but it still turns out an error instead of skipping over it.

Any advice on what to do? I'm completely lost with this.


Solution

  • // item element can be missed and you'll get bad access. Do not chain your calls that way
    
    tinyxml2::XMLElement* elementType = doc.FirstChildElement("item")->FirstChildElement("type");
    
    // element type can be missed, as well as attributes id and name
    string id = elementType->Attribute("id");
    string name = elementType->Attribute("name");
    cout << "id: " << id << endl;
    cout << "name: " << name << endl;
    }   
    

    Carefully check every element and attribute. Do not chain calls because every call can return null. If you check all nullptr cases you'll find your error