【问题标题】:debug assertion failed: dbgheap.cpp and dbgdell.cpp调试断言失败:dbgheap.cpp 和 dbgdell.cpp
【发布时间】:2026-02-12 09:55:01
【问题描述】:

我有某种内存泄漏问题。我在前面的几行中有它,但我通过编写一个复制赋值构造函数来纠正它。但问题出在delete newB 行。当我注释掉该行时,会弹出另一个错误。你认为我在哪里有一些内存泄漏,因为我知道它与内存分配有某种关系。

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++;
    }
}

如果您需要,我也可以向您展示 Branch 类,因为它也可能与构造函数或析构函数有关,但我未能成功纠正这些错误,因为此错误继续弹出。

编辑:对不起,我以为我说了。

【问题讨论】:

    标签: c++ memory-management heap-memory destructor


    【解决方案1】:

    它失败是因为最初 cntBranches==0 并且 allBranches 未初始化,正如我所假设的那样。
    因此,当第一次调用 addBranch
    allBranches[cntBranches] = *newB;
    将写入 allBranches 中垃圾指向的一些随机内存位置。
    通过其余的指针操作是不正确的,也会导致错误。例如
    delete[] tempArray;
    将删除之前分配的所有内容,让 allBranches 指向已删除的对象。所以我建议要么阅读更多关于指针是什么以及内存分配如何工作的信息,或者尽可能使用 std::vector。

    【讨论】:

    • 首先,我在构造函数中初始化它。 BankingSystem::BankingSystem(){ allBranches = new Branch[1]; allCustomers = new Customer[1]; allAccounts = new Account[1]; cntBranches = 0; cntCustomers = 0; cntAccounts = 0; nextAccountId = 1000; } 我以为我将它们复制到 allBranches[]in for 循环中。我看了很多关于它的视频,也阅读了一些,但仍然无法管理。
    • allBranches[i] = tempArray[i];在这里,您将覆盖 allBranches = new Branch[cntBranches+1]; 新创建的所有内容使它们泄漏内存的分支,然后使用 delete[] tempArray;您将删除 allBranches 中所有有用的内容,因为 tempArray 仍保存指向先前创建的数据的指针并将删除它们。仍然可以用一行代码替换所有这些代码 allBranches.push_back(Branch(id, name)); allBranches 为 std::vector
    • 那么for(int i = 0; i&lt;cntBranches; i++){ allBranches[i] = tempArray[i]; }for(int i = 0; i&lt;cntBranches; i++){ allBranches[i] = *new Branch(tempArray[i]); }在内存方面有什么区别?
    • 这会好一些,因为您将创建另一个分支副本(在不同的地址),以后不会使用 tempArray 删除它。通过它仍然会覆盖使用 Branch* tempArray = new Branch[cntBranches]; 创建的现有对象。并导致内存泄漏。
    • 那么我应该怎么做才能防止覆盖?今晚我会阅读更多关于它的资料,但我仍在为我的具体问题寻找一些答案。