0

i have allocated the following structure,using dataset_creator function, and i want to free this structure(dataset, i maen) with all of its components. would you help me please??

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;
}

sorry for the grammatical mistakes; note:that is not the whole code;

2 Answers2

1

Take a look at the order:

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);

You have another allocation for your structure current_attribute so free that memory also

free(current_attribute->next);
Gopi
  • 19,784
  • 4
  • 24
  • 36
1

For every pointer in your data structure, you must use free, and also for the structure itself. But make sure the pointers you are freeing aren't used somewhere else. Also, if you have nested pointers (e.g. struct attribute **hash_table), you have to take care of the pointers inside the pointers as well.

Philipp Murry
  • 1,660
  • 9
  • 13