-1

I have a some kind of memory leak problem. I had it in earlier lines, but i corrected it by writing a copy assignment constructor. But the problem is on the delete newB line. When i comment out that line, there is another error popping out. Where do you think i have some memory leaks because i know it is somehow related with the memory allocation.

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

I can show you the Branch class too if you need it because it may be related with constructors or destructor too, but i was not successful at correcting those as this error continues to pop out.

Edit: Sorry, i thought i stated it.

enter image description here

4

1 回答 1

0

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

于 2013-04-07T16:33:26.827 回答