我相信以下有一个理性的解释,但我有点困惑.
问题在于创建一个_TCHAR [CONSTANT],一个_TCHAR *的函数,并连接它们并返回结果.
由于某种原因,来自_tmain()的whatTheHeck()的调用返回乱码.
_TCHAR* whatTheHeck(_TCHAR* name) { _TCHAR Buffer[BUFSIZE]; DWORD dwRet; dwRet = GetCurrentDirectory(BUFSIZE,Buffer); _TCHAR* what = new _TCHAR[BUFSIZE]; what = _tcscat(Buffer,TEXT("\\")); what = _tcscat(what,name); return what; } int _tmain(int argc,_TCHAR* argv[]) { _TCHAR* failure = whatTheHeck(TEXT("gibberish);")); // not again .. _tprintf(TEXT("|--> %s\n"),failure); _TCHAR* success = createFileName(TEXT("readme.txt")); // much better _tprintf(TEXT("|--> %s\n"),success); return 0; }
相比之下,当堆东西按预期工作时.
_TCHAR* createFileName(_TCHAR* name) { _TCHAR* Buffer = new _TCHAR[BUFSIZE]; DWORD dwRet; dwRet = GetCurrentDirectory(BUFSIZE,Buffer); Buffer = _tcscat(Buffer,TEXT("\\")); Buffer = _tcscat(Buffer,name); return Buffer; }
为什么有区别?
是因为_tcscat()连接内存地址而不是其内容并返回清除堆栈?
解决方法
你的代码有很多问题.让我们分开,我们应该:
_TCHAR* whatTheHeck(_TCHAR* name) // We're inside a local scope { _TCHAR Buffer[BUFSIZE]; // "Buffer" has automatic storage _TCHAR* what = new _TCHAR[BUFSIZE]; // "what" points to newly allocated dyn. memory what = _tcscat(Buffer,TEXT("\\")); // Oh no,we overwrite "what" - leak! // Now what == Buffer. what = _tcscat(what,name); // Equivalent to "_tcscat(Buffer,name)" return Buffer; // WTPF? We're returning a local automatic! }
正如你所看到的,你们都是引起内存泄漏的一个有意思和鲁莽的新功能,你也在一生之后返回一个本地对象的地址!
我强烈推荐
阅读documentation for strcat
,了解“来源”和“目的地”,>不使用strcat,而是像strncat一样更安全的版本,>不使用strncat,而是std :: string.