Detect memory leak when placement new is used using sanitizer

129 Views Asked by At

How force sanitiser to detect memory leaks when memory allocation takes place in a predefined storage? Below an example

#include <iostream>
#include <type_traits>
class A
{

};
typename std::aligned_storage<256, alignof(256)>::type store;
A * foo()
{
    return  new (&store) A();
}
A * bar()
{
    return  new  A();
}
int main() {
    A * a = foo();
    a     = foo();

    A * a2 = bar();
    a2 = bar(); 
}

When bar is called memory leak is detected. But no when foo is called Demo

1

There are 1 best solutions below

0
On

Your A is "trivially destructible", which means (quote taken from cppref docs for std::is_trivially_destructible):

Storage occupied by trivially destructible objects may be reused without calling the destructor.

Moreover, there is no memory leak from calling foo several times, because foo itself does not allocate any memory.

This code is totally fine and there is no reason for a sanitzier to complain:

#include <iostream>
#include <type_traits>
class A
{

};
typename std::aligned_storage<256, alignof(256)>::type store;
A * foo()
{
    return  new (&store) A();
}
int main() {
    A * a = foo();
    a     = foo();
    std::cout << std::is_trivially_destructible<A>::value;
}

Output is

 1