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();

}
1
  • 3
    You only delete if you new'd. Commented Jul 7, 2013 at 22:41

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

OK - So if instead of a vector of int *, I had some Objects * (instantiated by new), then it would have worked?
@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".
@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.
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.