Search code examples
c++vectormemory-leaksaddress-sanitizer

Why memory leaks if i add vector<int> to class that I use to create an array by new[]


I wrote this code:

#include <iostream>
#include <memory>
using namespace std;

class G {
public:
    vector<int> v = {1};
};

int main() {
    G* t = new G[5];
    new (t) G();
    delete [] t;
}

I compile this by this way:

clang++ -std=c++20 -fsanitize=address b.cpp -o main -Werror && ./main

sanitizer detects memory leaks, 4 byte due to I add vector v = {1} to class G. Without this vector it works normally. Tell me please what is the problem, i dont understand.

I expected that that code will work normally. I expected that vector v will be destructed by standard destructor.


Solution

  • G* t = new G[5]; constructs 5 G with vectors t[0]..t[4].

    new (t) G(); constructs a new G and its vector at t[0] again, without destroying the previously constructed G object and its vector at that storage. You need to destroy the old objects before overwriting them:

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class G {
    public:
        vector<int> v = {1};
    };
    
    int main() {
        G* t = new G[5];
        t[0].~G(); // <-- add this
        new (t) G();
        delete [] t;
    }