gpt4 book ai didi

c - C中的动态数组无法释放内存

转载 作者:行者123 更新时间:2023-11-30 17:40:54 26 4
gpt4 key购买 nike

在释放 freeArray 中的 g.content.array 期间,程序崩溃。怎么了?

  #define STR_SHORT 256

struct DirFileArray {
struct dirFile *array;
size_t used;
size_t size;
};

struct dirFile
{
int contentType ;
char name [STR_SHORT];
struct DirFileArray content;
};

struct dirFile * getDirFile(char * fileName)
{
struct dirFile * f= (struct dirFile *) malloc(sizeof(struct dirFile ) );
f->contentType=TYPE_NONE;
strcpy(f->name,fileName);
f->content.array=NULL ;

return f;
};

void freeArray(struct DirFileArray *a) {
if (a->array)
{
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
}
void insertArray(struct DirFileArray *a, struct dirFile * element)
{

if (a->used == a->size)
{
a->size ++;
a->array =realloc(a->array, a->size * sizeof(struct dirFile));
}
a->array[a->used++] = *element;
}

void killDirFile(struct dirFile * value)
{

int i;
for (i=0; i<value->content.used;i++ )
{

killDirFile( & value->content.array[i]);

}

printf("freeing array of %s\n", value->name);
freeArray(&value->content);
printf("freeing %s\n", value->name);

free(value);
value=NULL;

}

int main(void)
{
struct dirFile * g = getDirFile("ggg");
struct dirFile * c = getDirFile("ccc");
insertArray(&g->content,c);
killDirFile(g);

}

输出:

freeing array of ccc
freeing ccc
freeing array of ccc
freeing ccc
freeing array of ggg
*** glibc detected *** /home/pro/fff/Debug/updDown: corrupted double-linked list: 0x00000000006e9160 ***

最佳答案

看起来usedsize从未初始化过。

关于c - C中的动态数组无法释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com