使用Tinyxml的分段错误
问题描述:
我试图读取一个Xml文件递归地使用Tinyxml,但是当我尝试访问数据时,我得到一个“分段错误”。这里是代码:使用Tinyxml的分段错误
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);
出于某种原因,这三个“如果”行抛出我的分段错误,但我已经不是哪里出了问题的想法。
在此先感谢。
答
在每次迭代开始时,Your're正在更新ingrediente
,然后在检查它不为空之前解引用它。如果它为空,这将给出分段错误。该循环应该沿着
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();
}
这样的行构成:对不起,有些英文混入变量名;我不会说西班牙语。
或者,如果NextSiblingElement
给你当你开始迭代的第一要素,在for
可以用while
取代:
while ((ingrediente = ingrediente->NextSiblingElement("Ingrediente")))
重要的一点是让指针后检查空,并取消引用前。
它看起来像你检查如果ingrediente!= NULL在第三,如果但不是在前两个。如果ingrediente真的是空的,那么前两个if会抛出一个分段错误。你应该用调试器打开它,以确定什么是NULL。 – Pace 2010-08-14 00:05:12
如果您发布一个完整的代码,您会得到一个精确的答案,并且不要忘记使用“代码”标签,以便正确格式化。我建议你编辑。 – Poni 2010-08-14 00:18:40
如果你发布你正在解析的XML的“迷你版本”,你会做得更好。 – Poni 2010-08-14 00:19:46