2012-12-13 35 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 。从技术上讲,该缓冲器是返回