【问题标题】:C11 - Realloc on array of structs fails when doing realloc twiceC11 - 执行 realloc 两次时,结构数组上的 Realloc 失败
【发布时间】:2020-03-07 06:32:58
【问题描述】:

我正在尝试使用 malloc 和 realloc 来保存一个结构数组。数组应该动态增长,大小应该每次增加 10 个结构元素。

结构:

typedef struct
{
    unsigned char foreign_word_[100] = {0};
    unsigned char native_word_[100] = {0};
} VocabularyCouple;

在我的 main 中,我使用 malloc 初始化数组:

VocabularyCouple* VocStruct = (VocabularyCouple*)malloc(sizeof(*VocStruct) * 10);

增加 struct-array 的大小似乎在 main 中可以正常工作...

VocabularyCouple* temp = (VocabularyCouple*)realloc(VocStruct, (sizeof(VocabularyCouple) * 20));

if (temp == NULL)
{
    printf("ERROR: Out of Memory\n");
    return 4;
}
else
{
    VocStruct = temp;
    free(temp);
    temp = NULL;
}

但是,如果我将 realloc-part 放入这样的函数中:

uint8_t resizeVoc(uint32_t new_size, VocabularyCouple **VocStruct)
{
    VocabularyCouple *temp = (VocabularyCouple*)realloc(*VocStruct, (sizeof(VocabularyCouple) * new_size));
    ...
}

我只能调用该函数一次。其他所有调用都会导致此错误:

HEAP[VocTest.exe]: Invalid address specified to RtlValidateHeap( 01300000, 01308500 )

除非我遗漏了什么,否则这应该与c - Realloc an array of Structs 的问题相同,但我就是无法让它工作。

感谢您的帮助!

【问题讨论】:

  • 请不要在这里修复代码,如果需要,请发布一个新问题。
  • 非常感谢,您解决了我的问题。我尝试设置VocStruct = &temp 而不是*VocStruct = temp;
  • typedef struct { unsigned char foreign_word_[100] = {0}; unsigned char native_word_[100] = {0}; } VocabularyCouple; 是什么语言?

标签: c arrays struct malloc realloc


【解决方案1】:
VocStruct = temp;
free(temp);

这是错误的,您在分配内存后立即释放所有内存。 VocStructtemp 指向同一个内存区域。只需删除free()

为了澄清,temp 指针就在那里,以防realloc 失败。如果您编写 VocStruct = realloc(VocStruct, ...realloc 失败,那么您将使用 NULL 覆盖指向已分配内存的唯一指针并造成内存泄漏。但是你只有 1 块内存——即使有 2 个指针同时指向它。

【讨论】:

  • 哦,对了,多么愚蠢的错误。但是,我在函数中没有 free(),所以问题仍然存在。
  • @Heinzable 闻起来像未定义的行为。它在 main() 中从来没有正常工作过,只是运气不好。但是您可以修复该错误,然后发布一个新问题。确保它是minimal reproducible example
  • @Heinzable 也许你忘记在resizeVoc 函数中分配*VocStruct = temp;,所以调用者仍在使用旧的、不再有效的内存位置。
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 2013-09-19
  • 2012-09-19
  • 2014-07-21
相关资源
最近更新 更多