以下是List
ADT,
typedef struct List{
void **array;
/* Following members for Housekeeping - Array enhancement*/
int lastItemPosition;
int size;
}List;
#define INITIAL_LIST_SIZE 50
createList
操作会尝试free(*(list->array))
期望释放void*
数组,但不会释放指向每个void*
的对象,因为listPointer
采用浅层副本list
List *createList(List *list, Op opType){
List *listPointer = (List *)malloc(sizeof(List));
void *accumulator = NULL;
if(opType == CREATE_NEW_LIST){
accumulator = malloc(INITIAL_LIST_SIZE*sizeof(void*));
listPointer->array = &accumulator;
/* Is it safe to initialise zero to element of array of void* pointers? */
listPointer->array = memset(listPointer->array, 0, INITIAL_LIST_SIZE*sizeof(void *));
listPointer->lastItemPosition = -1;
listPointer->size = INITIAL_LIST_SIZE;
}else if(opType == DOUBLE_THE_LIST){
accumulator = malloc(2*(list->size)*sizeof(void *));
listPointer->array = &accumulator;
/* Performing shallow copy, Is deep copy required? */
listPointer->array = memcpy(listPointer->array, list->array, list->size*sizeof(void*));
listPointer->lastItemPosition = list->lastItemPosition;;
listPointer->size = 2*(list->size);
free(*(list->array)); // How to free list pointer and its members?
}else if(opType == HALF_THE_LIST){
accumulator = malloc(((list->size)/2)*sizeof(void *));
listPointer->array = &accumulator;
/* Performing shallow copy, Is deep copy required? */
listPointer->array = memcpy(listPointer->array, list->array, (list->size/2)*sizeof(void *));
listPointer->lastItemPosition = list->lastItemPosition;
listPointer->size = (list->size)/2;
free(*(list->array)); // How to free list pointer and its members?
}
return listPointer;
}
执行以下列表操作List
,
void insertItem(List *, void *newItem);
void deleteItem(List *, int listIndex);
用户访问,
/* main.c */
#include"list.h"
int main(void){
List *arrayList = createList((List *)NULL, CREATE_NEW_LIST);
if (arrayList == (List *)NULL){
fprintf(stderr, "Unable to createList() \n");
exit(1); //Nothing else to do without arrayList
}
/* Objects should be on heap */
int *object = malloc(sizeof(int));
*object = 650;
insertItem(arrayList, object);
}
问题:
请您澄清一下,我的代码中free(*(list-> array))的作用是什么?
答案 0 :(得分:1)
以下代码剪辑应该完成这项工作:
else if(opType == DOUBLE_THE_LIST){
listPointer->array = realloc(listPointer->array, 2*(list->size)*sizeof(void *));
listPointer->lastItemPosition = list->lastItemPosition;;
listPointer->size = 2*(list->size);
// do not free any more: free(*(list->array)); // How to free list pointer and its members?
}
答案 1 :(得分:0)
对于选项DOUBLE_THE_LIST
和选项HALF_THE_LIST
,您的代码将使用现有list
进行调用。
然后代码创建一个新列表,并将现有列表的全部或一半复制到新列表中。
然后使用free(*(list->array));
最后,使用return listPointer;
因此,在使用带有这些选项的函数时,应始终将返回值分配给与用作参数的列表相同的列表。那就是:
myList = createList(myList, HALF_THE_LIST);
如果你这样做:
myListB = createList(myListA, HALF_THE_LIST);
你myListA
指向已经免费的内存,这是不好的。