8

解决QT程序异常中止,报错__acrt_first_block == header

 2 years ago
source link: https://segmentfault.com/a/1190000040991901
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解决QT程序异常中止,报错__acrt_first_block == header

发布于 今天 10:33
  • 在Windows下使用VS开发QT程序,如果使用了函数toStdString来将QString转换为std::string的时候,可能会发生崩溃,报错__acrt_first_block == header。
  • 这种崩溃会发生在vs项目的运行库设置为静态链接(/MT)时,如果运行库设置的是动态链接(/MD)则不会有问题。
  • 这个崩溃的根本原因是对象在析构时释放内存不正确。std::string是STL中定义的模板类,所以编译器在编译dll时会将std::string实例化,在编译exe时也会将其实例化。当设置运行库为静态链接(/MT)时,dll和exe都有自己独立的heap内存。函数toStdString会返回一个std::string,这个std::string是在dll的内存中分配的,当其在exe中被释放时就会抛出__acrt_first_block == header的异常。
  • 这个问题在QT的官方bugreports里也有人反馈——QString::toStdString() bug——按照官方的说法这不是QT的bug,是微软编译器的实现问题。
  • 所以,这个问题的解决方法就是:

    1. 设置dll和exe的运行库为动态链接(/MD)。
    2. 让dll的接口不要返回std::string。
    3. 使用toLocal8Bit替换toStdString。例如,将

      std::string fs = qsFilter.toStdString();
      std::string fs = std::string(qsFilter.toLocal8Bit());

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK