-1
我有一種內存泄漏問題。我在早期的版本中使用過,但我通過編寫一個複製分配構造函數來糾正它。但問題是在delete newB
線。當我註釋掉該行時,會彈出另一個錯誤。你認爲我在哪裏有一些內存泄漏,因爲我知道它與內存分配有某種關係。調試斷言失敗:dbgheap.cpp和dbgdell.cpp
void BankingSystem::addBranch(const int id, const string name){
if(isBranchExisting(id)){
cout << "\n\tBranch " << id << " already exists. Please try it with another id number.";
}
else if(!isBranchExisting(id)){
Branch* tempArray = new Branch[cntBranches];
if(cntBranches != 0){
for(int i = 0; i<cntBranches; i++){
tempArray[i] = allBranches[i];
}
delete[] allBranches;
allBranches = new Branch[cntBranches+1];
for(int i = 0; i<cntBranches; i++){
allBranches[i] = tempArray[i];
}
allBranches[cntBranches] = Branch(id, name);
delete[] tempArray;
}
Branch* newB = new Branch(id,name);
allBranches[cntBranches] = *newB;
cout << "\n\tBranch " << id << " is added successfully.";
delete newB;
cntBranches++;
}
}
我可以告訴你科類太多,如果你需要它,因爲它可能與構造函數和析構函數也有關係,但我沒有成功糾正那些爲這個錯誤繼續彈出。
編輯:對不起,我以爲我說過。
首先,我在構造函數中初始化它。 'BankingSystem :: BankingSystem(){ \t allBranches = new Branch [1]; \t allCustomers = new Customer [1]; \t allAccounts = new Account [1]; \t cntBranches = 0; \t cntCustomers = 0; \t cntAccounts = 0; \t nextAccountId = 1000; }' 我以爲我將它們複製到for循環的allBranches []中。我看了很多關於它的視頻,也看了一些,但仍然無法管理它。 – 2013-04-07 16:38:16
allBranches [i] = tempArray [i];這裏您將覆蓋allBranches = new Branch [cntBranches + 1];分支使他們泄漏內存,然後用delete [] tempArray;您將刪除allBranches中有用的所有內容,因爲tempArray仍保存指向先前創建的數據的指針,並將刪除它們。而且所有這些代碼都可以用一行代替allBranches.push_back(Branch(id,name)); allBranches是std :: vector –
alexrider
2013-04-07 16:50:34
那麼 'for(int i = 0; i
2013-04-07 17:20:07