我的一部分代码将从文本文件中读入未知数量的行,将该行解析成一个结构体(tempSomeStruct),调整 SomeStruct_Array 的大小,然后将 tempSomeStruct 添加到新开辟的内存空间中。
然而,在经过几次 while 循环后,我的程序停止运行并显示如下信息:
“myApplication.exe已触发断点”
我没有设置断点,深入挖掘后,看起来断点是由于我对 realloc 的调用引起的堆栈损坏。我在动态分配方面比较新手,虽然我已经搜索并找到了一些可能的原因,但到目前为止还没有找到任何解决方法。
在这种情况下,我是如何破坏堆栈的?我应该采取哪些不同的方法以避免这样做?
我有这样一个函数:
然而,在经过几次 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;
}
}
realloc
创建了一个大小为totalSize
的数组,并返回totalSize
。因此,在realloc
之后,数组的大小恰好为SomeStruct_Array_Size
,而不是多一个。 - nneonneo