我的部分代码将从文本文件中读取未知数量的行,将该行解析为结构(tempSomeStruct),调整 SomeStruct_Array 的大小,然后将该 tempSomeStruct 添加到内存中新打开的位置。
但是经过几次while循环后,我的程序停止并说
myApplication.exe 已触发断点。
我没有设置断点,并且进行了一些挖掘,看起来断点是由于我调用 realloc 造成的堆损坏。我对动态分配很陌生,所以虽然我已经搜索并找到了一些可能的原因,但到目前为止还没有修复工作。
在这种情况下我是如何破坏堆的,我有什么不同的做法来避免这样做?
我有这样的功能:
int growArray(SomeStruct **SomeStruct_Array,int currentSize, int numNewElements)
{
const int totalSize = currentSize + numNewElements;
SomeStruct *temp = (SomeStruct*)realloc(*SomeStruct_Array,(totalSize * sizeof(SomeStruct)));
if (temp == NULL)
{
printf("Cannot allocate more memory.\n");
return 0;
}
else
{
*SomeStruct_Array = temp;
}
return totalSize;
}
它在其他地方被这样调用:
SomeStruct* SomeStruct_Array = (SomeStruct *) calloc(1,sizeof(SomeStruct));
int Error_Array_Size = 0;
if(SomeStruct_Array == NULL)
{
printf("Cannot allocate initial memory for data\n");
return;
}
while(fgets(line,sizeof(line), file) != NULL)
{
parseTextIntoSomeStruct(line, &tempSomeStruct);
SomeStruct_Array_Size = growArray(&SomeStruct_Array,SomeStruct_Array_Size,1);
if(SomeStruct_Array_Size > 0)
{
SomeStruct_Array[SomeStruct_Array_Size] = tempSomeStruct;
}
}