0
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 函数分配的任何内存而不会使我的程序崩溃?

4

1 回答 1

1

尝试以下

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

代替

ArrayList *n = malloc(sizeof(ArrayList));
于 2013-05-30T05:46:34.777 回答