简体   繁体   中英

Freeing Dynamic Array of Char*

I have a struct "ListStruct" that is basicly a dynamic array of a struct "Info". Here is how i create the ListStruct:

void initArray(ListStruct *a, size_t initialSize)
{
    a->array = malloc(initialSize * sizeof(Info));
    a->used = 0;
    a->size = initialSize;
}

The struct "Info" has a few ints in it and it has an int keySize and a char* key. This is how i allocate the "char* key" in the Info struct:

element->key = malloc(keySize*sizeof(char));

On my freeArray function, i'm getting a "double free or corruption" error right on the 2nd iteration of the loop. Here is the code:

void freeArray(ListStruct *a)
{
    int temp;
    for(temp=0; temp<a->used; temp++)
    {
        free(a->array[temp].key);
        a->array[temp].key=NULL;
        //reset some ints
    }

    free(a->array);
    a->array = NULL;
    a->used = a->size = 0;
}

This is probably a dumb mistake, but what am i doing wrong?

EDIT: found bug. Check comments for solution

Found mistake. I was adding the same Info variable 5 times to the list (for testing). Since it was the same variable, it was the same memory region and i was allocating it once while trying to free it 5 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM