在 C 语言中动态重新分配一个结构体数组

3
我的一部分代码将从文本文件中读入未知数量的行,将该行解析成一个结构体(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;
   }
}
1个回答

1
你的新数组大小为SomeStruct_Array_Size,而你立即写入了SomeStruct_Array[SomeStruct_Array_Size],这是超出数组末尾的一个元素!记住,C数组从零开始索引。
SomeStruct_Array[SomeStruct_Array_Size-1] = tempSomeStruct;

代替之。

我在代码中添加了一些内容,这个示例中忽略了的是我将大小初始化为0,并且在分配 someStruct 前已经有了1个空间。因此,它应该是一个有效的数组位置。 - Xantham
不对,仍然不正确。你的 realloc 创建了一个大小为 totalSize 的数组,并返回 totalSize。因此,在 realloc 之后,数组的大小恰好为 SomeStruct_Array_Size,而不是多一个。 - nneonneo
哦……我明白了,所以在我的第一次循环中,由于我的初始化是错误的(说大小为0,而实际上为1),所以我只是重新分配了我已经分配的同样大小的区域。因此,在它可以达到SomeStruct_Array [0] 的高度时,我正在写入 SomeStruct_Array[1]。我认为这个错误比简单的“Off by one”错误更高级。 - Xantham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接