堆损坏检测到双端数组

时间:2013-12-03 23:36:23

标签: c++ arrays heap corruption

运行以下代码时出现堆损坏错误...

   bool Deque::insertBack(int input)
    {
        cout << "Back is " << back << endl;
        if(isFull() == 0)
         {
            Array[back] = input;
            back = (back - 1) % size;
            return true;
         }else{
             cout << "Deque is Full " << input << " not inserted" << endl;
            return false;
        }
    }

我似乎无法解决这个问题,而且我已经玩了很长一段时间,而且我的insertFront功能也正常。

这是全班......

Deque::Deque(int iSize)
{
    size = iSize;
    Array = new int[size]; // initialise array size
    front = 0;
    back = 0;
}

Deque::~Deque()
{
  delete [] Array; 
}

bool Deque::isFull()
{
    bool full = false;
    cout << back << " " << ((front + 1) % size) << endl;
    if(back < (front + 1) % size)
    {
        // deque is full
        full = true;
    }
    else
    {   
        full = false;
    }
    return full;
}

bool Deque::insertFront(int input)
{   
    cout << "Front is " << front << endl;
    if(isFull() == 0)
        {
           Array[front] = input;
           front = (front + 1) % size;
           return true;
        }else{
        cout << "Deque is Full " << input << " not inserted" << endl;
    return false;
    }
}

bool Deque::insertBack(int input)
{
    cout << "Back is " << back << endl;
    if(isFull() == 0)
     {
        Array[back] = input;
        back = (back - 1) % size;
        return true;
     }else{
         cout << "Deque is Full " << input << " not inserted" << endl;
        return false;
    }
}

void Deque::displayDeque()
{
    for(int i=back;i < front;i++)
    {
        cout << Array[i] << " is at postion " << i << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

这可能是导致堆损坏的问题:

    back = (back - 1) % size;

在C ++中,取负数的模数会得到负数。所以你可以使用:

获得相同的效果
    back = (back + size-1) % size;

此外,您的displayQueue()函数未考虑i的模数。