C++ debug 系列:手动调用析构函数

博客分析了学弟C++程序输出后RE的原因,是对象析构时多此一举导致double free。还介绍了placement new的正规操作,包括持有内存、分配对象等步骤。此外,解释了第一次析构未出现问题是因构造的vector平凡,还给出更简单的复现crash的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struct A
{
    vector<int> v;
    int a;

    A(int _a=0)
    {
        cout<<"construct!"<<endl;
        a=_a;
        new (&v) vector<int>(_a,0);
    }

    
    ~A()
    {
        cout<<"destroy!"<<endl;
        v.~vector<int>();
        a=0;
    }
} fxxk;


void main()
{
    for (int i=0;i<100;i++)
    {
        fxxk.~A();
        cout<<1<<endl;
        new (&fxxk) A(100000);
    }

}

来自学弟的一个程序,在进行了如下输出之后会 RE。
在这里插入图片描述

原因

对象析构时在自己的析构函数执行完毕后会依次调用成员的析构函数。

~A() 里面的 ~vector<int>() 多此一举,导致了 double free

其他

placement new 的正规操作:

  1. 首先持有可用的内存空间,常用途径有申请字符数组,内存池等。
  2. placement new 分配对象 T * t = new (ptr) T
  3. 正常使用对象 t.exec()
  4. 销毁对象 t.~T()
  5. 重复循环 2-4,直到结束
  6. 归还内存空间

代码中 main 函数对 placement new 的使用是没问题的。

update

有人问既然析构会导致 double free,为什么第一次析构没有出现?

这是因为第一次构造的 vector 是平凡的,它的三个指针(start,end,end_cap)都是 nullptr ,不需要析构。

template <class _Tp, class _Allocator>
__vector_base<_Tp, _Allocator>::~__vector_base()
{
    if (__begin_ != nullptr)
    {
        clear();
        __alloc_traits::deallocate(__alloc(), __begin_, capacity());
    }
}

所以更简单的复现 case 只需要构造一个非平凡的 A,不用进行任何的操作就可以复现 crash

#include <vector>
#include <iostream>

using namespace std;

struct A
{
    vector<int> v;
    int a;

    A(int _a=0)
    {
        cout<<"construct!"<<endl;
        a=_a;
        new (&v) vector<int>(_a,0);
    }

    ~A()
    {
        cout<<"destroy!"<<endl;
        v.~vector<int>();
        a=0;
    }
} fxxk(1);

int main() {

}

/Users/lf/repos/untitled/cmake-build-debug/untitled
construct!
destroy!
untitled(25973,0x11daf5e00) malloc: *** error for object 0x7feb1d6043f0: pointer being freed was not allocated
untitled(25973,0x11daf5e00) malloc: *** set a breakpoint in malloc_error_break to debug

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值