当前位置:   article > 正文

c++中包含string成员的结构体拷贝导致的double free问题_c++ str_format double free

c++ str_format double free

最近调试代码遇到一个的问题,提示double free,但是找了好久也没有找到释放两次的地方,后来调试发现,是由于使用了一个包含string成员的结构体,这个结构体使用memcpy拷贝导致的问题;

 

代码如下:

  1. #include <stdio.h>
  2. #include <map>
  3. #include <string>
  4. #include <stdlib.h>
  5. #include <memory>
  6. #include <iostream>
  7. #include <string.h>
  8. using namespace std;
  9. typedef struct TestPtrInfo
  10. {
  11. string name;
  12. int data;
  13. }TestPtrInfoSt;
  14. class testPtr
  15. {
  16. public:
  17. testPtr(int i,TestPtrInfoSt* info):m_id(i)
  18. {
  19. memcpy(&m_info, info, sizeof(TestPtrInfoSt)); //导致出问题的这一行
  20. cout<<m_id<<" name: "<<m_info.name<<" testPtr start..."<<endl;
  21. }
  22. ~testPtr()
  23. {
  24. cout<<m_id<<" name: "<<m_info.name<<" testPtr end..."<<endl;
  25. }
  26. private:
  27. int m_id;
  28. TestPtrInfoSt m_info;
  29. };
  30. int main()
  31. {
  32. //map<string, shared_ptr<testPtr> >testMap;
  33. map<string, testPtr* >testMap;
  34. TestPtrInfoSt info;
  35. for (int i = 0; i < 10 ; i++ )
  36. {
  37. info.name = "no-"+to_string(i);
  38. testMap[to_string(i)] = new testPtr(i, &info);
  39. }
  40. auto iterPtr = testMap.find("1");
  41. delete iterPtr->second;
  42. testMap.erase(iterPtr);
  43. cout <<"1, reslease "<<endl;
  44. return 0;
  45. }

这个不是正式代码,用测试代码复现的问题;

编译没问题,运行时会挂掉:

如上图,会报段错误,用gdb调试,打印堆栈信息如下:

从上面的堆栈信息中,看到这么一行:

#2  0xb7f4a985 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() ()
   from /usr/lib/i386-linux-gnu/libstdc++.so.6

 

这里是string类的析构函数,在这里想到可能是memcpy拷贝结构体导致的,修改后测试不会再出现问题。

关于包含类的结构体,一般不能使用memcpy拷贝,会出问题。

参见:

memcpy复制字符串的注意事项/memcpy不能用来拷贝类类型 - hchacha - 博客园
https://www.cnblogs.com/hchacha/p/7615631.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/194868
推荐阅读
相关标签
  

闽ICP备14008679号