大佬教程收集整理的这篇文章主要介绍了c – 使用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)
这就是为什么您需要使用复制构造函数或将另一个赋值给另一个(即使用覆盖的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,s2.size(),s2.c_str());
您将对其他类对象执行类似的步骤.
以上是大佬教程为你收集整理的c – 使用memcpy复制对象时,双重释放或损坏错误全部内容,希望文章能够帮你解决c – 使用memcpy复制对象时,双重释放或损坏错误所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。