AnyOne
AnyOne

Reputation: 21

C11 - Realloc on array of structs fails when doing realloc twice

I'm trying to use malloc and realloc to hold an array of structs. The array should dynamically grow, size should increase by 10 struct elements every time.

Struct:

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

In my main, I initialize the array with malloc:

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

Increasing the size of the struct-array seems to work fine in 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;
}

However, if I put the realloc-part into a function like this:

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

I can only call the function once. Every other call will result in this error:

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

Unless I'm missing something, this should be the same problem as c - Realloc an array of Structs, but I just can't get it to work.

Thank you for your help!

Upvotes: 2

Views: 200

Answers (1)

Lundin
Lundin

Reputation: 213842

VocStruct = temp;
free(temp);

This is wrong, you free all memory as soon as you have allocated it. VocStruct and temp point at the same memory area. Just remove the free().

To clarify, the temp pointer is just there in case realloc fails. Had you written VocStruct = realloc(VocStruct, ... and realloc fails, then you would have overwritten the only pointer to the allocated memory with NULL and created a memory leak. But you only ever have 1 chunk of memory - even though 2 pointers point at it at the same time.

Upvotes: 3

Related Questions