0

Everytime I run a method called Loan &removeFirst () {} my program keeps on crashing. The program crashes whenever I attempt to delete the temporary Loan structure that I created. I can show some background for the container class and the code for my function:

class ListOfLoans {

public:

    //default constructor allocate appropriate heap storage 
    //store elements on heap array declared like this: 
    //new Loan*[initial_size];
    ListOfLoans(int initial_size = 4) {
        elements = new Loan*[initial_size];
        numberOfElements = 0;
        capacity = initial_size;
        index = 0;
    }

    ~ListOfLoans(void) {
        cout << "Deleting \n";
        delete [] elements;
    }


    // answer the first element from the list but don't remove it
    Loan & first() const {
        if (capacity == 0) {
            cout << "Attempted on empty list. Exitting!" << endl;
            exit;
        } else {
            return *elements[0];
        }
    }

    // answer the first element from the list and remove it from the list
    // if the resulting list is more than three quarters empty release some memory
Loan & removeFirst() {
    index--;

    if (capacity == 0) {
           cout << "Attempted on empty list. Exitting!" << endl;
           exit;
    }

    if(size() < capacity/4) {  //shrink the container when 1/4 full 
      cout << "shrinking\n"; 
      Loan **temp = elements; 
      elements = new Loan*[capacity/2]; 
      for(index = (numberOfElements - 1); index >= 0; index--) {elements[index] = temp[index];}
      capacity /= 2; 
      delete [] temp; // my program crashes at this line, I want to delete the temp structure
    } 
      return first();
    }


private: 

    Loan ** elements; 
    int     numberOfElements; //number of elements in the list 
    int     capacity; //size of the available array memory 
    mutable int index; //used to help with the iteration

};
4

2 回答 2

1

删除指针数组(指向指针的指针)时,通常会执行以下操作:

for(int i = 0; i < capacity; ++i)
{
    delete temp[i];
}
delete [] temp;

如果没有 for 循环,您将泄漏内部指针中的内存。

size() 是否返回 numberOfElements?我在这里担心的是,您的 for 循环将数据从 temp 复制到元素中,并且可能从 temp 范围之外开始。如果是这种情况,您可能正在覆盖可能是崩溃源的内存。为什么不直接从 0 循环到 size()?如果要删除第一个元素,只需使用以下内容复制它:

elements[index] = temp[index+1];

最后,如果要删除列表中的第一个元素,那么 first() 在内部会做什么?从我上面看到的情况来看,您似乎已经删除了第一个元素,或者打算这样做。如果它被删除,它可能会在您返回它时被删除,因此您需要在本地复制该指针并让您的 for 循环删除所有元素跳过第一个元素,以便您仍然有一些有效的返回!

于 2013-10-07T03:31:28.523 回答
1

您不提供 size() 的实现。它只返回 numberOfElements 吗?如果没有,那可能是你的问题。如果 numberOfElements > capacity/2,您的循环会破坏堆,导致最后崩溃。

如果 size() 返回 numberOfElements,我发现此代码存在很多问题,但根据您提供的信息,不是崩溃的根源。

于 2013-10-07T03:36:01.213 回答