[英]GetCurrentDirectory() is breaking the code in C++
在下面的代碼中,如果我注釋掉對“ GetCurrentDirectory”的調用,則一切正常,但是,如果我不這樣做,則代碼在此之后中斷,沒有子窗口出現,但程序不會崩潰。 編譯器沒有給出任何錯誤。
char *iniFilePath;
int lenWritten = GetCurrentDirectory( MAX_PATH, iniFilePath );
if( lenWritten )
{
lstrcat( iniFilePath, iniFileName.c_str() );
char *buffer;
GetPrivateProfileString( iniServerSectionName.c_str(), serverIp.c_str(), "", buffer, MAX_PATH, iniFilePath );// server ip
MessageBox( 0, buffer, 0, 0 );
}
else
{
MessageBox( 0,0,0,0 );
}
iniFilePath
是GetCurrentDirectory()
試圖寫入的未初始化的指針,從而導致未定義的行為。 GetCurrentDirectory()
不會為調用方分配緩沖區:必須提供它。
改成:
char iniFilePath[MAX_PATH]; // or similar.
與其使用lstrcat()
在其參考頁上具有警告不要使用消息lstrcat()
,而是使用std::string
構造路徑,以避免潛在的緩沖區溢出:
const std::string full_file_path(std::string(iniFilePath) + "/" + iniFileName);
請注意Wimmel指出的與buffer
類似的問題。
我這樣做是為了獲得當前目錄-
int pathLength = GetCurrentDirectory(0, NULL);
std::vector<char> iniFilePath(pathLength);
GetCurrentDirectory(pathLength, iniFilePath.data());
但是請注意,這不是線程安全的,因為該目錄可以在兩次調用之間從另一個線程更改,但是據我所知,很少有程序會更改當前目錄,因此這不太可能成為問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.