使用sanitizer使用placement new时检测内存泄漏

问题描述 投票:0回答:1

当内存分配发生在预定义存储中时,如何强制清理程序检测内存泄漏? 下面是一个例子

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

当调用bar时检测到内存泄漏。 但是当 foo 被调用时不会 演示

c++ memory-leaks address-sanitizer
1个回答
0
投票

您的

A
是“微不足道的可破坏”,这意味着(引用自
std::trivially_destructible
的 cppref 文档):

可以重用普通可破坏对象占用的存储空间,而无需调用析构函数。

多次调用

foo
不会导致内存泄漏,因为
foo
本身不分配任何内存。

这段代码完全没问题,清理人员没有理由抱怨:

#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;
}

输出为

 1
© www.soinside.com 2019 - 2024. All rights reserved.