0

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
Rocafort8
  • 15
  • 3
  • It looks like you check if ingrediente!=NULL on the third if but not on the first two. If ingrediente really was null then those first two if's would throw a segmentation fault. You should open this up with a debugger to find out exactly what is NULL. – Pace Aug 14 '10 at 00:05
  • You'd get a precise answer if you'd post a complete code, and don't forget to use the "code" tag so it gets formatted properly. I suggest you edit. – Poni Aug 14 '10 at 00:18
  • And you'll do even better if you'll post a "mini-version" of the XML you're parsing. – Poni Aug 14 '10 at 00:19

1 Answers1

1

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
  • 249,747
  • 28
  • 448
  • 644