一个关于使用基指针删除子进程分配内存的奇怪案例

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

This question may be similar to others but I couldn't find my case so here it goes。对不起,如果它已经在某处得到回答。

假设我们有基本结构 A。在许多地方,我们从该结构派生子结构。对于一个操作,我们持有一个指向 A 的共享指针,假设我们用

f(void* child_data, size_t size_of_child)
的函数设置该指针。在该函数中,我们希望将 child 的数据复制到缓冲区,然后将共享指针 A 的现有数据复制到它上面(因此我希望我们将 child 的数据附加到 A 的现有数据?)。所以我尝试创建一个具有给定
void* buffer
参数大小的
size_of_child
然后
memcpy
child_data
到它。之后我
memcpy
现有A的数据,希望附加数据。

演示代码如下。

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


struct A
{
    uint64_t first = 0;
  
    virtual ~A() = default;
};

struct B : public A
{
    uint64_t second = 0;
};

int main()
{
    // this will act like the existing data.
    A a;
    a.first = 12;
    
    // this is the new data.
    B b;
    b.first = 3;
    b.second = 5;
    
    // in the case, we only have the information about the size of b, so we i believe
    // cannot create it with new.
    void* Buffer = std::malloc(sizeof(B));
    
    // copy the data of b to buffer.
    std::memcpy(Buffer, &b, sizeof(B));

    // copy the data of a to buffer where i hope it will leave the data of A.
    std::memcpy(Buffer, &a, sizeof(A));
    

    // now this will act like our shared pointer. At some point it will get deleted.
    A* ap = (A*)Buffer;
   
    std::cout << "b = " << (*(B*)Buffer).first << std::endl;
    std::cout << "b = " << (*(B*)Buffer).second << std::endl;
    
    // deleted here
    delete ap;
    
    std::cout << "b = " << (*(B*)Buffer).first << std::endl;
    std::cout << "b = " << (*(B*)Buffer).second << std::endl;
   
    return 0;
}

它按预期附加数据但是当指针 ap get 被删除时,看起来它只删除了 A 的内存块。所以这是输出。

b = 12
b = 5
b = 11681007486144092754
b = 5

那么这是否意味着它是内存泄漏?为什么删除不了成员

second

c++ memory-management heap-memory
© www.soinside.com 2019 - 2024. All rights reserved.