gpt4 book ai didi

c - 释放与列表关联的任何动态分配的内存并返回 NULL?

转载 作者:行者123 更新时间:2023-11-30 15:48:24 24 4
gpt4 key购买 nike

typedef struct ArrayList
{
// We will store an array of strings (i.e., an array of char arrays)
char **array;

// Size of list (i.e., number of elements that have been added to the array)
int size;

// Length of the array (i.e., the array's current maximum capacity)
int capacity;

} ArrayList;

我有这个函数,它使用上面的结构为字符串数组动态分配内存:

ArrayList *createArrayList(int length){


ArrayList *n = malloc(sizeof(ArrayList));


int initial = 0, i;
n->size = initial;


if (length > DEFAULT_INIT_LEN)
{

n->array = malloc(length * sizeof(char*));
n->capacity = length;

if (n->array == NULL)
panic("ERROR: out of memory in Mylist!\n");

for (i = 0; i< n->capacity; i++)
{
n->array[i] = NULL;
}

}
else
{
n->array = malloc(DEFAULT_INIT_LEN * sizeof(char*));
n->capacity = DEFAULT_INIT_LEN;

if (n->array == NULL)
panic("ERROR: out of memory in Mylist!\n");

for (i = 0; i< n->capacity; i++)
{
n->array[i] = NULL;
}

}

printf("-> Created new ArrayList of size %d\n", n->capacity);


return n;

}

我的问题是每次我尝试在 main 中调用此函数时我的程序都会崩溃:

ArrayList *destroyArrayList(ArrayList *list)
{


free(list);


return NULL;

}

如何正确实现 destroyArrayList 函数来释放 createArrayList 函数分配的任何内存而不会使程序崩溃?

最佳答案

尝试以下操作

static ArrayList *n = malloc(sizeof(ArrayList));

而不是

ArrayList *n = malloc(sizeof(ArrayList));

关于c - 释放与列表关联的任何动态分配的内存并返回 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826219/

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