【问题标题】:Placing function in .dll causes debug assertion failed error在 .dll 中放置函数会导致调试断言失败错误
【发布时间】:2010-11-02 12:02:24
【问题描述】:

大家好,

我今天遇到了一个非常奇怪的问题,我不确定是什么原因造成的。这是我用来获取当前工作目录的函数:

#ifdef _WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#error "There is currently no support for non windows based systems!"
#endif

const std::string getCurrentPath()
{
   char CurrentPath{_MAX_PATH];
   GetCurrentDir(CurrentPath, _MAX_PATH);
   CurrentPath[_MAX_PATH - 1] = '/0';
   return std::string(CurrentPath);
}

此函数作为独立函数运行良好。但是,如果我将其声明为类中的静态函数:

static __declspec(dllexport) const std::string getCurrentPath(void);

和一个 .dll,当我尝试这样做时,我得到“调试断言失败错误”

std::cout<<CUtilities::getCurrentPath()<<std::endl;

如果我改为写:

std::string dir = CUtilities::getCurrentPath();
std::cout<<"Dir is : "<<dir<<std::endl;

它工作正常。我对自己做错了什么感到完全困惑。有什么想法吗?

【问题讨论】:

    标签: dll getcwd


    【解决方案1】:

    我终于发现了问题所在。该项目是使用 /MT 选项编译的,因此 .dll 的堆与原始文件不同。因此,当字符串大小大于其初始大小 (15) 时,将从 .dll 一侧分配堆。然而,该字符串从主程序端调用了它的析构函数,然后析构函数试图从 .dll 的堆中释放内存,从而导致“堆损坏错误”

    解决方案是简单地使用 /MD 选项进行编译。

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多