堆损坏在VS中检测到错误,但在其他IDE中工作良好

Heap corruption detected error in VS, but working fine with other IDE

本文关键字:其他 IDE 工作 错误 VS 损坏 检测      更新时间:2023-10-16

我正在使用VoidPtr做一些事情,当我在其他IDE(如Quincy或Eclipse)上测试我的代码时,我运行它们没有任何问题。

然而,当我试图在Visual Studio 2015中运行我的代码时,显示很好,但我偶然发现了一个名为

的错误

HEAP corrupt DETECTED: after Normal block #138 at (some address)

我无法找到错误的位置,因为它显示了一个指针的地址,这对我来说更难调试。

我正在尝试联合两个void指针数组的数据。

void unionAnimalArray(VoidPtr* animalArray, int size, VoidPtr* animalArray2, int size2)
{
    int sizeu;
    VoidPtr *vpArray = &animalArray[0];
    VoidPtr *vpArray2 = &animalArray2[0];
    VoidPtr *end = &animalArray2[size2];
    VoidPtr *su = new VoidPtr[12];
    su = animalArray;
    sizeu = size;
    VoidPtr tempu;
    bool check;
    while (vpArray2 != end)
    {
        do
        {
            tempu = *vpArray2;
            check = true;
            for (int j = 0; j<size; j++)
            {
                if (j == 0)
                    vpArray = &animalArray[0];
                if (*(static_cast<Animal*>(tempu)) == *(static_cast<Animal*>(*vpArray)))
                {
                    check = false;
                    break;
                }
                ++vpArray;
            }
            if (!check)
                ++vpArray2;
        } while (!check && vpArray2 != end);
        if (vpArray2 != end)
        {
            vpArray = &su[sizeu];
            *vpArray = tempu;
            ++sizeu;
            ++vpArray2;
        }
    }
    cout << "The union is" << endl;
    cout << "t{";
    printAnimalArray(su, sizeu);
    delete[]su;
}
void unionAnimalArray(VoidPtr* animalArray, int size, VoidPtr* animalArray2, int size2)
...
VoidPtr *su = new VoidPtr[12]; // su points to new memory
su = animalArray; // su now points to same memory as animalArray2
...
delete[]su; // deletes memory shared with animalArray2

数组应该按元素复制而不是赋值:

for(int i = 0; i < size2; ++i) {
    su[i] = animalArray[i];
}

你可以在自动内存中保存缓冲区su,因为你知道在编译时缓冲区的大小:

VoidPtr su[12];

考虑一下:

VoidPtr *su = new VoidPtr[12];
su = animalArray;

12个新的VoidPtr-s去哪里了?谁和何时将被删除?