2012-12-13 37 views
0
HMODULE m_LangDll; 

wchar_t* GetString(const int StringID) 
{ 
    wchar_t* nn = {0}; 
    if (m_LangDll) 
    { 
     wchar_t temp[2048]; 
     if(::LoadString(m_LangDll, StringID, temp, 2048)) 
     { 
      MessageBox(0, L"string found", 0, 0); 
      nn = temp; 
      return nn; 
     } 
    } 

    //assert(s.length() && _T("String not found!")); 
    return 0; 
} 

此代碼工作得很好。它返回我想要的字符串沒問題。從DLL字符串表中獲取字符串

如果我刪除MessageBox(0,L「未找到字符串」,0,0),它不會。它返回一個隨機字符。我顯然做錯了什麼。我只是不明白如何看似不相關的MessageBox(0,0,0,0)調用有任何影響。

我已經嘗試用其他代碼替換MessageBox調用。像分配更多的wchar_t *,但它似乎與調用MessageBox有關。

我一直在呼籲的GetString像...

MessageBox(0, GetString(101),L"HHHHH", 0); 

,我得到一個不同的一堆jibberish,當我這樣稱呼它......

wchar_t* tempString = GetString(101); 
MessageBox(0, tempString, 0, 0); 

但是這兩種方式的工作只要我不GetString的註釋掉的MessageBox()

[編輯]

謝謝對於你的回覆,他們都非常有幫助。現在

我的代碼是

wchar_t* GetString(const int StringID) 
{ 
    wchar_t* nn = new wchar_t[2048]; 
    if (m_LangDll) 
    { 
     if(::LoadString(m_LangDll, StringID, nn, 2048)) 
     {  
     return nn; 
     } 
    } 
    delete [] nn; 
    //assert(s.length() && _T("String not found!")); 
    return 0; 
} 

感謝neagoegab更是如此。

還有一個問題。爲什麼MessageBox()使代碼有效?

+0

溫度是在堆疊之後無效...將被刪除...在} – neagoegab

+0

在這個表達式NN = {0}; - >你應該使用std :: nullptr而不是這個。 – neagoegab

+0

這只是偶然的是病態的代碼。未定義行爲意味着什麼事情都有可能發生。 – hmjd

回答

0

你從函數返回一個局部變量的地址,導致未定義的行爲:

nn = temp; // when the function returns temp is out of scope 
return nn; // and n is pointing at temp. 

返回std::wstring來代替,而c_str()訪問const wchar_t*表示。

0

你的臨時變量是在棧上... alocate它堆:

HMODULE m_LangDll; 

wchar_t* GetString(const int StringID) 
{ 
    wchar_t* nn = new wchar_t[2048]; 
    if (m_LangDll) 
    { 
     if(::LoadString(m_LangDll, StringID, nn, 2048)) 
     { 
      MessageBox(0, L"string found", 0, 0); 
      nn = temp; 
      return nn; 
     } 
    } 

    delete [] nn; 
    //assert(s.length() && _T("String not found!")); 
    return 0; 
} 
0

也許,一個問題是,GetString的()返回一個指針來緩衝堆棧(「臨時」局部變量)上llocated 。從技術上講,該緩衝器是返回