调用delete []时出现C ++ HEAP错误

时间:2012-04-06 10:38:04

标签: c++ arrays heap delete-operator

我一直在VS 2100中收到错误“CRT检测到应用程序在启动堆缓冲区之前写入内存”

有人可以帮忙吗?我的主要是一直在底部。在operator = function

上运行delete []命令时发生错误
#include "intset.h"
const int MAXINITIALSIZE = 5;
int IntSet::numOfArray = 0;

IntSet::IntSet(int a, int b, int c, int d, int e)
{
    numOfArray++;
    int tempArray[] = {a, b, c, d, e};
    size = determineHighest(tempArray) + 1; //determines largest int
    cout << "size is " << size << endl;

    arrayPtr = new bool[size]; //creates array of bool

    for (int i = 0; i < size; i++) //fill bool array 
    {
        arrayPtr[i]= false;  //arrayptr is a bool pointer created in the header
    }   

    for (int i = 0; i < MAXINITIALSIZE; i++)
    {
        arrayPtr[tempArray[i]]= true;
    }

        for (int i = 0; i < size; i++)
    {
        cout << &arrayPtr[i] << endl;
    }
}
IntSet::IntSet(const IntSet &intsetObject)
{
    numOfArray++;
    size = intsetObject.size;

    arrayPtr = new bool[size];

    for (int i = 0; i < size; i++)
    {
        if (intsetObject.arrayPtr[i])
            arrayPtr[i] = intsetObject.arrayPtr[i];
    }
}
IntSet::~IntSet()
{
    --numOfArray;
    delete [] arrayPtr;     
    arrayPtr = NULL;
}

int IntSet::determineHighest(int tempArray[])
{
    int temp = tempArray[0];    
    for (int i = 1; i < MAXINITIALSIZE; i++)
    {
        if (tempArray[i] > temp)
            temp = tempArray[i];
        else
            continue;       
    }
    return temp;
}

IntSet& IntSet::operator=(const IntSet &intsetObject) //ask about IntSet&
{
    cout << "inside operator=" << endl;
    if (&intsetObject != this)
    {
        for (int i = 0; i < size; i++)
        {
            cout << &arrayPtr[i] << endl;
        }
        delete [] arrayPtr;   //HEAP ERROR HERE!
        for (int i = 0; i < size; i++)
        {
            cout << &arrayPtr[i] << endl;
        }
        size = intsetObject.size
        arrayPtr = new bool[size]();
        for (int i = 0; i < size; i++)
        {
            if (intsetObject.arrayPtr[i])
                arrayPtr[i] = intsetObject.arrayPtr[i];
        }
    }
    return *this;
}
ostream& operator<<(ostream &output, const IntSet &intsetObject)
{
    output << "{ ";
    for (int i = 0; i < intsetObject.size; i++)
    {
        if (intsetObject.arrayPtr[i] == true)
        {
            output << i << " ";
        }
        else 
            continue;
    }
    output << "}";
    return output;
}


//main

#include "intset.h"

int main() {

    IntSet object2(9);   

    IntSet object4(3,6);

    object4 = object2;

   return 0;
}

1 个答案:

答案 0 :(得分:0)

只有使用负索引访问arrayPtr时才会发生这种情况。我怀疑在IntSet::IntSet的声明中你的a,b,c,d,e的默认值是-1,所以它在set-true循环中写入arrayPtr [-1]。检查tempArray[i] >= 0那里。

此外,你删除后不能打印数组,所以你应该在删除后删除这些行,虽然它们应该是“无害的”,因为只会打印垃圾,但是谁知道 - 操作系统可以释放包含该数组的页面,它可能会破坏您的程序。

最后,您不应该在副本和版本中测试if (intsetObject.arrayPtr[i])=运营商。否则,源数组中的所有“false”元素在目标数组中都未初始化(new bool[size] 将数组初始化为所有false)。