tags:

views:

52

answers:

1

I'm trying to read an Xml file recursively using Tinyxml, but when I try to acces the data I get a "Segmentation Fault". here is the code :

int id=0, categoria=0;
const char* nombre;
do{  
    ingrediente = ingrediente->NextSiblingElement("Ingrediente");   
    contador++;  
    if(ingrediente->Attribute("id")!=NULL)
        id = atoi( ingrediente->Attribute("id") );  
    if(ingrediente->Attribute("categoria")!=NULL)
        categoria = atoi ( ingrediente->Attribute("categoria") );  
    if(ingrediente!=NULL)
        nombre = ( ( ingrediente->FirstChild() )->ToText() )->Value();  
}while(ingrediente);    

For some reason, the three "if" lines throws me the Segmentation Fault but I've not idea about where is the problem.

Thanks in advance.

+1  A: 

Your're updating ingrediente at the start of each iteration, and then dereferencing it before you check that it's not null. This will give a segmentation fault if it is null. The loop should probably be structured along the lines of

for (ingrediente = first_ingrediente; 
     ingrediente; 
     ingrediente = ingrediente->NextSiblingElement("Ingrediente"))
    contador++;  
    if(ingrediente->Attribute("id"))
        id = atoi( ingrediente->Attribute("id") );  
    if(ingrediente->Attribute("categoria"))
        categoria = atoi ( ingrediente->Attribute("categoria") );  
    nombre = ingrediente->FirstChild()->ToText()->Value();  
}

Sorry for mixing some English into the variable names; I don't speak Spanish.

Or, if NextSiblingElement gives you the first element when you start iterating, the for can be replaced with while:

while ((ingrediente = ingrediente->NextSiblingElement("Ingrediente")))

The important point is to check for null after getting the pointer, and before dereferencing it.

Mike Seymour