加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用memcpy复制对象时,双重释放或损坏错误

发布时间:2020-12-16 03:08:19 所属栏目:百科 来源:网络整理
导读:我有如下代码: #include iostream#include string#include cstringstruct test { std::string name; size_t id;};int main() { test t; t.name = "147.8.179.239"; t.id = 10; char a[sizeof(t)] = ""; std::memcpy(a,t,sizeof(t)); test b; std::memcpy(b,
我有如下代码:
#include <iostream>
#include <string>
#include <cstring>

struct test {
    std::string name;
    size_t id;
};


int main() {
    test t;
    t.name = "147.8.179.239";
    t.id = 10;

    char a[sizeof(t)] = "";
    std::memcpy(a,&t,sizeof(t));

    test b;
    std::memcpy(&b,a,sizeof(t)); 

    std::cout << b.name << " " << b.id << std::endl;
}

当我编译它并运行它,它给我以下错误:

147.8.179.239 10
*** Error in `./test': double free or corruption (fasttop): 0x0000000000bf9c20 ***
Aborted (core dumped)

原来,代码可以打印出结果.但是如何解决这个错误?

解决方法

通过使用memcpy的方式,你有两个完全相同的std :: string对象.这包括他们可能在内部使用的任何指针.所以当每个对象的析构函数运行时,它们都试图释放相同的指针.

这就是为什么您需要使用复制构造函数或将另一个赋值给另一个(即使用覆盖的operator =).它知道这些实现差异并正确处理它们,即为目标对象分配单独的内存缓冲区.

如果要提取std :: string中包含的字符串,则需要将对象序列化为已知的表示形式.那么你可以反序列化它来转换它.

std::string s1 = "hello";
printf("len=%zu,str=%sn",s1.size(),s1.c_str());

// serialize
char *c = new char[s1.size()+1];
strcpy(c,s1.c_str());
printf("c=%sn",c);

// deserialize
std::string s2 = c;
printf("len=%zu,s2.size(),s2.c_str());

您将对其他类对象执行类似的步骤.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读