一、在程序设计中,某次意外操作realloc操作同一个地址,造成了其返回NULL异常。
realloc传入的指针与pCommandTemp指针所赋值不一致,在第三次realloc时必出现异常,
重启10次,现象稳定。
for(StopActionChild=mxmlFindElement(AutoChild,tree,"command",NULL,NULL,MXML_DESCEND);
StopActionChild!=NULL;
StopActionChild=StopActionChild->next->next)
{
pCommandTemp = (CommandInfo_t *)realloc((m_ProcInfos + m_ProcInfoNum)->ProcStopActions,sizeof(CommandInfo_t)*(CommandNum+1));
if(!pCommandTemp)
{
LOG_ERR("[appAutoProcLoadConfig-->realloc] pCommandTemp realloc error.\n");
free(m_ProcInfos);
m_ProcInfos=NULL;
mxmlDelete(tree); /*删除xml文件句柄*/
fclose(fp); /*关闭文件*/
return -1;
}
(m_ProcInfos+m_ProcInfoNum)->JudgeParamInfos->StopCommands = pCommandTemp;
memcpy(((m_ProcInfos+m_ProcInfoNum)->JudgeParamInfos->StopCommands+CommandNum)->Name, mxmlElementGetAttr(StopActionChild,"name"),30);
memcpy(((m_ProcInfos+m_ProcInfoNum)->JudgeParamInfos->StopCommands+CommandNum)->Type, mxmlElementGetAttr(StopActionChild,"type"),30);
((m_ProcInfos+m_ProcInfoNum)->JudgeParamInfos->StopCommands+CommandNum)->Tab = atoi(mxmlElementGetAttr(StopActionChild,"tab"));
((m_ProcInfos+m_ProcInfoNum)->JudgeParamInfos->StopCommands+CommandNum)->Code = atoi(mxmlElementGetAttr(StopActionChild,"code"));
CommandNum++;/*停止动作计数递增*/
}
(m_ProcInfos+m_ProcInfoNum)->JudgeParamInfos->StopCmdNum = CommandNum;
调试结果:
二、编写独立realloc测试程序,首先malloc一个commad结构体,然后重复用commad地址realloc,会在第三个循环出现异常,重启10次,故障现象稳定。
void exam_01()
{
CommandInfo_t * pCommandTemp=NULL;
CommandInfo_t * command=(CommandInfo_t * )malloc(sizeof(CommandInfo_t *));
int i;
for(i=0;i<100;i++)
{
pCommandTemp=(CommandInfo_t *)realloc(command,sizeof(CommandInfo_t )*(i+1));
LOG_WARN("\n<>realloc test: < pCommandTemp:0x%x,m_ProcInfoNum:%d,CommandNum:%d>
\n",pCommandTemp,0,i);
if(!pCommandTemp)
{
LOG_ERR("pCommandTemp realloc error.\n");
return;
}
}
}
调试结果:
关于realloc对同一个地址重复操作会出现返回NULL结果疑问,目前寻找资料未能找到合理解释,该种现象的原理?