3

I am trying to understand how to delete a vector of pointers, and the pointed objects, in memory. I have started with a simple example, found in another thread, but I get "pointer being freed was not allocated" error.

What I am doing wrong?

#include <vector>
#include <algorithm>
#include <iostream>

int main(){
    std::vector <int *> vec;

    int a = 2;
    int * b = &a;

    int c = 3;
    int * d  = &c;

    vec.push_back(b);
    vec.push_back(d);

    for (int i = 0; i < vec.size(); i++) {
        delete vec[i];
    }
    vec.clear();

}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Béatrice Moissinac
  • 934
  • 2
  • 16
  • 41

3 Answers3

3

Only call delete on variables that were created with new Check this link: Calling delete on variable allocated on the stack

Community
  • 1
  • 1
hanslovsky
  • 870
  • 6
  • 21
  • OK - So if instead of a vector of int *, I had some Objects * (instantiated by new), then it would have worked? – Béatrice Moissinac Jul 07 '13 at 22:34
  • 3
    @Bibi541 If you had a vector of `int*` full of elements instantiated by `new`, it would have worked. `int*` just means "address of an `int`" -- not "reference to an `int` I own". – Yakk - Adam Nevraumont Jul 07 '13 at 22:36
  • @Bibi541, Then you'd realize that cleaning them up yourself was a royal pain, especially in terms of exception-safety, and you'd use a smart pointer and live happily forever after. – chris Jul 07 '13 at 23:55
2

You're deallocating memory that was allocated on the stack with automatic storage. That's why you're getting errors.

Only delete things you allocated with new. RAII will take care of the rest.

user123
  • 8,970
  • 2
  • 31
  • 52
0

When you do

int a = 2;

You are allocating a int on stack and anything on stack does not need to delete, it will be freed automatically once we left the scope it is declared. Therefore in your code, you are trying to free the same thing twice.

Whilst if you do

int* a = new int(2);

You will then allocate a int on heap, where data will not be deleted unless you explicitly call delete.

The bottom line is, new and delete should always be written in pairs.

Zijun
  • 58
  • 5