简体   繁体   English

释放Char *的动态数组

[英]Freeing Dynamic Array of Char*

I have a struct "ListStruct" that is basicly a dynamic array of a struct "Info". 我有一个结构“ ListStruct”,基本上是结构“ Info”的动态数组。 Here is how i create the ListStruct: 这是我创建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. 结构“ Info”中包含一些int,并且具有int keySize和char *键。 This is how i allocate the "char* key" in the Info struct: 这就是我在Info结构中分配“ char *键”的方式:

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. 在我的freeArray函数上,我在循环的第二次迭代中收到“双重释放或损坏”错误。 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). 我将相同的Info变量添加了5次到列表中(用于测试)。 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. 由于它是相同的变量,所以它是相同的内存区域,我在尝试将其释放5次时分配了一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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