Search code examples
c++vectornew-operatordelete-operator

Vector with dynamically allocated memory cannot delete the last


In my code I have a vector that holds integers. Using the first loop I create 100 new integers and push them on the vector. The next loop then deletes all the dynamically allocated integers with the exception of the last, because the deletion of the last integer causes the error and returns 0xc0000005. Why does my program crash with the deletion of the last integer?

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> list;

    cout << list.size() << endl;

    int i = 0;
    while(i!=100)
    {
        list.push_back(*(new int(12)));
        i++;
    }

    cout << list.size() << endl;

    i=0;
    while(i!=99)
    {
        delete &list.back();
        list.pop_back();
        i++;
    }
/*
    delete &list.back();

    list.pop_back();
*/
    cout << list.size() << endl;

    return 0;
}

Solution

  • You are not doing what you think you are. What are pushed in to the vector are not dynamically allocated ints but a copy of the values of the dynamically allocated ints.

    So on this part

    list.push_back(*(new int(12)));
    

    you create a new int on heap with value 12 and then copy its value in to the vector. So you can not do

    delete &list.back();
    

    on the ints.

    That fact tat you had to take the address of the value should tell you that it is actually not a pointer in there.


    If you want to store the pointers then use

    vector<int*> list;
              ^^
    

    and push like

    list.push_back(new int(12));
    

    and you can delete as

    delete list.back();
    

    However just don't do it. No need to dynamically allocate ints. use

    vector<int> list;
    list.push_back(12);
    // Nothing needs to be deleted.