Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete objects from vector of pointers to object? [duplicate]

Tags:

c++

memory

vector

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

}
like image 707
Béatrice Moissinac Avatar asked Jun 01 '26 15:06

Béatrice Moissinac


1 Answers

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

like image 188
hanslovsky Avatar answered Jun 04 '26 07:06

hanslovsky