Bryan
Bryan

Reputation: 8697

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

I'm doing something with VoidPtr and when i tested out my codes on other IDE such as Quincy or Eclipse, I don't have any problem running them.

However, when i tried to run my codes in Visual Studio 2015, the display is fine, but i stumbled upon an error called

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

I can't locate where is the error because it is displaying the address of a pointer which is even harder for me to debug.

I'm trying to union the data of 2 void pointer array.

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;

}

Upvotes: 0

Views: 102

Answers (2)

Teivaz
Teivaz

Reputation: 5675

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

An array should be copied element-wise instead of assignment:

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

You can keep buffer su in automatic memory as you know the size of buffer in compile time:

VoidPtr su[12];

Upvotes: 1

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20739

Think a little bit about this:

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

Where did the 12 new VoidPtr-s go? Who and when they will be deleted ?

Upvotes: 0

Related Questions