我在寫代碼,它的很大一部分需要返回wchar數組。返回wstrings不是一個真正的選擇(雖然我可以使用它們),我知道我可以傳遞一個指針作爲參數並填充它,但是我特別想要返回一個指向這個寬字符數組的指針。最初的幾次迭代中,我發現我會返回數組,但在處理和打印時,內存將被覆蓋,而我將留下亂碼。爲了解決這個問題,我開始使用wcsdup,它固定了所有的東西,但是我正努力去準確地掌握正在發生的事情,因此,它應該被調用以便它能夠正常工作,而且我不會泄漏任何內存。實際上,每次我返回一個字符串時,我幾乎都會使用wcsdup,並且每次返回一個字符串時,我都知道會泄漏內存。這是我正在做的。我在哪裏以及爲什麼要使用wcsdup,或者有沒有比wcsdup更好的解決方案?你如何最好地利用wcsdup?
wchar_t *intToWChar(int toConvert, int base)
{
wchar_t converted[12];
/* Conversion happens... */
return converted;
}
wchar_t *intToHexWChar(int toConvert)
{
/* Largest int is 8 hex digits, plus "0x", plus /0 is 11 characters. */
wchar_t converted[11];
/* Prefix with "0x" for hex string. */
converted[0] = L'0';
converted[1] = L'x';
/* Populate the rest of converted with the number in hex. */
wchar_t *hexString = intToWChar(toConvert, 16);
wcscpy((converted + 2), hexString);
return converted;
}
int main()
{
wchar_t *hexConversion = intToHexWChar(12345);
/* Other code. */
/* Without wcsdup calls, this spits out gibberish. */
wcout << "12345 in Hex is " << hexConversion << endl;
}
「intToWChar」和「intToHexWChar」均返回指向函數完成後超出範圍的變量的指針。不要這樣做。 – crashmstr
你不需要[wcout](http://stackoverflow.com/questions/2493785/how-i-can-print-the-wchar-t-values-to-console)嗎? – crashmstr
爲什麼你不能只返回一個std :: wstring而不是原始指針? – paulm