QString::toStdString() crashes on std::string dest

2019-06-15 06:57发布

I've been debugging this for 2 hours now, and it boils down to this. If I call QString::toStdString

QString s = "testtesttesttesttesttest";
const std::string &temp = s.toStdString();

the program later crashes on std::string destructor

__CLR_OR_THIS_CALL ~basic_string()
    {   // destroy the string
    _Tidy(true); // <---- It crashes on this line.
    }

I thought it was memory corruption at first, but this happens even if main() contains only those 2 lines. Does anyone know why this happens, and also how can I fix it?

My Qt version is 4.8.1.

3条回答
够拽才男人
2楼-- · 2019-06-15 07:22

Most probable reason could be that your Runtime Library is "Multi-threaded (/MT)" and you need to change it to "Multi-threaded DLL (/MD)" (if you are on the release version)

If you are on the debug version change from "Multi-threaded Debug (/MTd)" to "Multi-threaded Debug DLL (/MDd)"

If you have an odd compilation of Qt, the solution should be the opposite.

You will find that on "Configuration properties->C/C++->Code Generation->Runtime Library"

查看更多
欢心
3楼-- · 2019-06-15 07:31

I tried tackling the problem a different way. I created a new project from Visual Studio, and the test code didn't crash there. Upon examining the differences between the *.vcproj files with WinMerge, I found that the crash is caused by some custom changes in the project concerning - you guessed it - the runtime libraries. This is the patch created by WinMerge with the minimum differences that cause the crash to be reproduced:

112c112
<               RuntimeLibrary="3"
---
>               RuntimeLibrary="1"
126a127,128
>               LinkLibraryDependencies="true"
>               UseLibraryDependencyInputs="false"
127a130,131
>               IgnoreAllDefaultLibraries="false"
>               IgnoreDefaultLibraryNames="msvcrtd.lib"
查看更多
何必那么认真
4楼-- · 2019-06-15 07:32

Your Qt DLLs need to be compiled with STL support and exactly the same C-Runtime Library as your code. It looks as though you are using two different CRTs at the same time, which would destroy the objects created on one heap by Qt into the heap used by your program.

Check the DLL Usage with the Dependency Walker!

查看更多
登录 后发表回答