我已经使用dataset_creator函数分配了以下结构,并且我希望将此结构(dataset,i maen)与其所有组件一起释放。 你能帮帮我吗?
struct dataset{
char *title;
struct linked_data *head;
struct dataset *next;
struct attribute **hash_table;
};
struct dataset* dataset_creator(char *name,struct attribute *expressions,struct query *query){
struct dataset *ds; //"ds" is the abbreviation of word "dataset"
//struct attribute **hash_table;
//struct linked_data *data;
struct attribute *current_attribute;
//int i;
int j;
int index;
ds=(struct dataset*)malloc(sizeof(struct dataset));
if(ds==NULL){
printf("failed memory allocation request\n");
exit(EXIT_FAILURE);
}
ds->next=NULL;
ds->title=(char*)calloc((strlen(name)+1),sizeof(char));
strcpy(ds->title,name);
ds->head=(linked_data*)malloc(sizeof(struct linked_data));
if(ds->head==NULL){
printf("failed memory allocation request\n");
exit(EXIT_FAILURE);
}
ds->head->next=NULL;
ds->hash_table=(attribute**)malloc(MAX_NUM_OF_ATTRS * sizeof(attribute*));
if(ds->hash_table==NULL){
printf("failed memory allocation request\n");
exit(EXIT_FAILURE);
}
for(j=0;j<MAX_NUM_OF_ATTRS;j++)
ds->hash_table[j]=NULL;
for(j=0;j<MAX_NUM_OF_ATTRS;j++){
index=hash(expressions[j].name,MAX_NUM_OF_ATTRS);
if(ds->hash_table[j]==NULL){
ds->hash_table[index]=(struct attribute*)malloc(sizeof(struct attribute));
ds->hash_table[index]->next=NULL;
}
else{
current_attribute=ds->hash_table[index]->next;
while(current_attribute->next != NULL){
current_attribute=current_attribute->next;
}
current_attribute->next=(struct attribute*)malloc(sizeof(struct attribute));
current_attribute->next->next=NULL;
}
}
return ds;
}
抱歉语法错误;
注意:这不是整个代码;
答案 0 :(得分:1)
看看订单:
1. free(ds->hash_table[index]); /* Free all the single pointers memory first in a loop*/
2. free(ds->hash_table);
3. free(ds->head);
4. free(ds->title):
5. free(ds);
您的结构current_attribute
还有另一个分配,所以也可以释放内存
free(current_attribute->next);
答案 1 :(得分:1)
对于数据结构中的每个指针,您必须使用free
,并且还必须使用结构本身。但请确保您释放的指针不会在其他地方使用。另外,如果你有嵌套指针(例如struct attribute **hash_table
),你也必须处理指针内的指针。