Heap corruption when returning from function inside a dll

被刻印的时光 ゝ 提交于 2019-12-03 13:25:39
bdonlan

Most likely, you're seeing crashes due to the fact that, in Windows, DLLs have their own private heap.

When you compiled your function, the compiler generated some code for std::string's destructor, to clean up its arguments. This code frees the allocated memory on the DLL heap. However, the application EXE also generates its own code for std::string's constructor, which allocates the code on the program heap. When you allocate on one heap and free on the other, undefined behavior occurs, and you crash.

As for why small strings don't trigger the bug - many std::string implementations inline small strings into the struct itself, to avoid heap overhead. When your string is small enough to fit, no memory allocation need take place, and thus it happens to appear to work... as long as you use the same STL version for both EXE and DLL, and the threshold for inlining never changes.

To avoid this issue, don't pass objects by value to DLLs (unless they are POD objects), and don't free an object in a different DLL or EXE than it was created in. Avoid passing STL or C++ library objects around as well, as their implementation may differ between different versions of the C++ compiler. Pass POD objects or C primitive types such as const char * instead.

When exporting DLL functions, it's best if they accept only integral data types, i.e. int or pointers (not sure about float and double).

When you need to pass a string, pass it as a const char *, when you need the DLL function to return a string, pass to the DLL a char * pointer to a pre-allocated buffer, where the DLL would write the string.

Never use memory allocated by the DLL outside of the DLL's own functions, and never pass by value structures that have their own constructor/destructor.

Probably you have linked with static version of C runtime, it is never a good idea to create a DLL that linked with static version of C runtime. This may cause many problems, for example in your program your EXE allocate memory from private heap of static C runtime that it is linked with it, then in your DLL you want to delete that heap and create a new heap(since you want to add some data to the input string and it need to grow its buffer), so it will cause an error. Simplest approach to this is to link all parts of your program(EXE and DLL) with DLL version of C runtime, so they all share same heap from MSVCRTXX.dll

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