简体   繁体   中英

Understanding Delete [] c++

Before all let me say that i have already search for an answer, and i can't find any that explains to me why i'm having problems.

Im a student and im now learning C++

So before tell me to not use C++ in this way, let me say to you that it is for learning purposes and understanding of some comcepts.

Program crashes at very last statement. delete[] tempVector; I cant understand why it happens since delete[] vector; works just fine.

The error: play with arr.exe has triggered a breakpoint

Please help me to understand what im doing wrong.

Thank you a lot.

class BetterArray
{
private:

    int* vector;
    int count;

public:

    BetterArray(int value);
    BetterArray(int* vec, int size);
    ~BetterArray();

    void add(int value);

    int* getArray();

};

BetterArray::BetterArray(int value)
{
   count = 1;

   vector = new int[1];
   vector[0] = value;   
 }

void BetterArray::add(int value){

    int* tempVector = new int[count + 1];

    for (int i = 0; i < count; i++)
        tempVector[i] = vector[i];

    tempVector[count] = value;

    count++;

    delete[] vector;

    vector = tempVector;

    delete[] tempVector; // programa crahses here.
}

Crash on delete is often a result of a heap corruption. When you assign the tempVector pointer to vector both pointer point to the same memory location. So deleting tempVector also deletes vector . vector now points to unassigned memory.

Now assuming you write to vector , you are writing to unassigned memory which will corrupt the heap. What happens after this is undefined behaviour but if the heap manager detects the corruption, it will often just crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM