2013-04-07 174 views
-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++; 
    } 
} 

我可以告訴你科類太多,如果你需要它,因爲它可能與構造函數和析構函數也有關係,但我沒有成功糾正那些爲這個錯誤繼續彈出。

編輯:對不起,我以爲我說過。

enter image description here

回答

0

它失敗,因爲最初cntBranches == 0和allBranches是未初始化的,因爲我承擔。
因此,當第一次調用addBranch
allBranches [cntBranches] = * newB;
將寫入allBranches中垃圾指向的一些隨機內存位置。
指針操作的其餘部分不正確,也會導致錯誤。例如
delete [] tempArray;
將刪除先前分配的所有分支指向已刪除對象的所有內容。所以我建議或者閱讀更多關於什麼指針以及mem分配是如何工作的,或者如果可能的話使用std :: vector。

+0

首先,我在構造函數中初始化它。 '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

+1

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

+0

那麼 'for(int i = 0; i 2013-04-07 17:20:07