when I reassign pointer-a to other data in memory, what happens to the data pointer-a was originally pointing at.
I'm asking because I am implementing some data structure methods using general algorithms for doing so, but I am a little concerned about some parts.
for example: here I am worried that I am not deleting the
temp_list
, I understand that
list
will be the one pointing at that data from now on and the data will get cleaned up by the destructor. But then what happens to the data
list
was orginally pointing at, is this going to leave random allocations in memory just floating around every function call?
Also I was taught that you should always delete anytime you use
new
but if I try to delete
temp_list
after I assign the old list the new values , I will get an error. Should I be trying to delete
temp_list
or is it okay to leave it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void ArrayList::add_front(int element){
//create new array, initialize first index
int* temp_list = new int [list_size+1];
temp_list[0] = element;
//fill rest of new array
for(int i = 0; i < list_size; i++){
temp_list[i+1] = list[i];
}
//update class list to equal new array
list_size++;
list = temp_list;
return;
}
|