使用memcpy复制对象时出现双重释放或损坏错误

时间:2016-08-18 13:11:28

标签: c++ struct memcpy

我有以下代码:

#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)

事实证明代码可以打印出结果。但是我该如何解决这个错误?

3 个答案:

答案 0 :(得分:17)

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

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

如果要提取std::string中包含的字符串,则需要序列化对象为已知表示。然后,您可以反序列化将其转换回来。

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

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

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

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

答案 1 :(得分:12)

你不能memcpy()test这样的非POD结构。您完全破坏了std::string成员。

必须使用复制构造函数来复制C ++对象。

答案 2 :(得分:6)

您获得双重免费错误的实际原因是,不是为变量ab创建新的字符串对象,而是复制引用(使用可变长度string)实现char *对象。

由于string析构函数在程序结束时释放了这个内存地址,并且如上所述,你有两个指向同一地址的字符串对象,你会得到一个双重自由错误

这将起作用,就像@JesperJuhl所说,你必须使用复制构造函数

#include <iostream>
#include <string>
#include <cstring>

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


int main()
{
    test t;
    test a;
    test b;

    t.name = "147.8.179.239";
    t.id = 10;

    a=t;
    b=t;

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