c++ memory error when using malloc/realloc/free on std::string

橙三吉。 提交于 2019-12-02 10:39:22

malloc(), free(), and realloc() are C library functions, that know absolutely nothing about C++ classes, their constructors, and destructors.

You are using malloc() with placement new to construct a std::string using malloc-ed memory. This is fine.

But then, you're using realloc() to reallocate the allocated memory.

Copying/moving C++ objects in memory must be done using the respective objects' copy/move constructors. Copying/moving C++ objects in memory cannot be done with realloc().

The only way to do this is to malloc() a new memory block, use placement new to invoke the objects' copy/move constructors in order to copy/move them into the new memory block, and finally invoke the destructor of the objects in the old memory block, after which it can be free()-ed.

realloc is not compatible with non-POD types.

Because it can move things in memory without the moved objects being aware of it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!