2013-04-07 110 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