Why does this program crash: passing of std::string between DLLs

前端 未结 6 1713
名媛妹妹
名媛妹妹 2020-11-29 02:28

I have some trouble figuring out why the following crashes (MSVC9):

//// the following compiles to A.dll with release runtime linked dynamically
//A.h
class          


        
6条回答
  •  旧巷少年郎
    2020-11-29 02:49

    You need to link to the same runtime lib (the DLL one), either debug or release, for every DLL in your app where memory is allocated in one and freed in another. (The reason for using the dynamically linked runtime lib is that then there will be one heap for your entire process, as opposed to one per dll/exe that links to the static one.)

    This includes returning std::string and stl-containers by value, as that is what you do.

    The reasons are twofold (updated section):

    • the classes have different layouts/sizes, so differently compiled code assumes data is in different places. Whoever created it first gets right, but the other one will cause a crash sooner or later.
    • the msvc heap-implementations are different in each runtime-lib which means that if you try to free a pointer in the heap that didn't allocate it, it will go bonkers. (This happens if the layouts are similar, i.e. where you outlive the first case.)

    So, get your runtime libs straight, or stop freeing/allocating in different dlls (i.e. stop passing stuff by value).

提交回复
热议问题