2010-11-02 55 views
0

你好夥伴,在.dll中放置函數會導致調試斷言失敗錯誤

今天我遇到了一個很奇怪的問題,我不完全確定是什麼導致它。這裏是我用來獲得當前工作目錄的功能:

#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; 

它工作正常。我對我做錯了什麼感到困惑。有任何想法嗎?

回答

1

我終於找出問題所在。該項目使用/ MT選項編譯,因此.dll與原始文件不同。所以當字符串大小大於初始大小(15)時,堆是從.dll的一端分配的。然而,該字符串是從主程序端調用的析構函數,然後析構函數試圖從.dll的堆中釋放內存,從而導致「堆損壞錯誤」

解決方案是使用/ MD選項簡單編譯。