1

我不断收到 VS 2100 中的错误“CRT 检测到应用程序在堆缓冲区开始之前写入内存”

任何人都可以帮忙吗?我的 int Main 一直在底部。delete []在 operator= 函数上运行命令时发生错误

#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;
}
4

1 回答 1

0

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

此外,删除后无法打印数组,因此您应该在删除后删除这些行,尽管它们应该是“无害的”,因为只会打印垃圾,但谁知道 - 操作系统可以释放页面包含数组,它可能会导致您的程序出现段错误。

最后,您不应该if (intsetObject.arrayPtr[i])在复制 &=运算符中进行测试。否则,源数组中的所有“假”元素在目标数组中都未new bool[size]初始化(不会将数组初始化为 all )。false

于 2012-04-06T10:48:52.907 回答