使用 Tinyxml 出现分段错误
我正在尝试使用 Tinyxml 递归地读取 Xml 文件,但是当我尝试访问数据时,出现“分段错误”。这是代码:
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);
出于某种原因,三个“if”行向我抛出了分段错误,但我不知道问题出在哪里。
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将在每次迭代开始时更新
ingrediente
,然后在检查它是否不为空之前取消引用它。如果它为空,这将产生分段错误。该循环的结构可能类似于“抱歉,在变量名称中混入了一些英语”;我不会说西班牙语。
或者,如果
NextSiblingElement
在开始迭代时为您提供第一个元素,则可以将for
替换为while
:重要的一点是检查null 在获取指针之后和取消引用它之前。
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 ofSorry 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, thefor
can be replaced withwhile
:The important point is to check for null after getting the pointer, and before dereferencing it.