Hello I'm new to c++ and trying to grasp the memory management in it with the free() and delete. I have this add_flat function which works fine until I try to free the memory. I created an FlatList object and added the flats .Without the delete statement it works fine but after I put it the Head just returns some garbage value. Should I define a destructor ? I'm very new in c++ so any help would be appreciated.
void FlatList::add_flat(int index,int initial_bandwith,int flat_id) {
Flat* new_flat = new Flat() ;
new_flat->id = flat_id ;
new_flat->initial_bandwidth = initial_bandwith ;
new_flat->is_empty = false ;
Flat* current = Head ;
if (index == 0 ) {
new_flat->next_Flat = Head ;
Head->prev_Flat = new_flat ;
Head = new_flat ;
}
else {
for (int i = 0 ; i < index ; i++) {
current = current->next_Flat ;
}
current->prev_Flat->next_Flat = new_flat ;
new_flat->prev_Flat = current->prev_Flat ;
current->prev_Flat = new_flat ;
new_flat->next_Flat = current ;
}
delete new_flat;
}
FlatList b ;
b.add_flat(0,10,1) ;
cout << b.Head->id ;