How to remove the first element from a container class in a C++ program? -
everytime run method called loan &removefirst () {} program keeps on crashing. program crashes whenever attempt delete temporary loan structure created. can show background container class , code function:
class listofloans { public: //default constructor allocate appropriate heap storage //store elements on heap array declared this: //new loan*[initial_size]; listofloans(int initial_size = 4) { elements = new loan*[initial_size]; numberofelements = 0; capacity = initial_size; index = 0; } ~listofloans(void) { cout << "deleting \n"; delete [] elements; } // answer first element list don't remove loan & first() const { if (capacity == 0) { cout << "attempted on empty list. exitting!" << endl; exit; } else { return *elements[0]; } } // answer first element list , remove list // if resulting list more 3 quarters empty release memory loan & removefirst() { index--; if (capacity == 0) { cout << "attempted on empty list. exitting!" << endl; exit; } if(size() < capacity/4) { //shrink container when 1/4 full cout << "shrinking\n"; loan **temp = elements; elements = new loan*[capacity/2]; for(index = (numberofelements - 1); index >= 0; index--) {elements[index] = temp[index];} capacity /= 2; delete [] temp; // program crashes @ line, want delete temp structure } return first(); } private: loan ** elements; int numberofelements; //number of elements in list int capacity; //size of available array memory mutable int index; //used iteration };
when deleting array of pointers (pointer pointer) typically following:
for(int = 0; < capacity; ++i) { delete temp[i]; } delete [] temp;
without loop, leak memory in internal pointer.
does size() return numberofelements? concern have here loop copies on data temp elements , may starting outside of range of temp. if case, overwriting memory may source of crash. why not loop 0 size()? if want remove first element, copy following:
elements[index] = temp[index+1];
finally, if removing first element in list, first() internally? i'm seeing above, appears have removed first element, or had intended to. if removed, may deleted time returning it, need copy pointer locally , have loop delete elements skip first 1 have still valid return!
Comments
Post a Comment