I have the following sample code:
CString CHttpsClient::converEncoding(LPWSTR originalString, long encodingType)
{
if (encodingType == CP_ACP) {
return CString(originalString);
}
CString ret;
int nBufferSize = MultiByteToWideChar(encodingType, 0, (LPCCH)originalString, -1, NULL, 0);
wchar_t *pBuffer = (wchar_t*)malloc(nBufferSize * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)originalString, -1, pBuffer, nBufferSize * sizeof(wchar_t));
ret = CString(pBuffer);
free(pBuffer);
return ret;
}
My question is when I invoke this method, I have freed memory of pBuffer, but this pBuffer still returned as CString(pBuffer), Will it cause memory leak or segfault when using CString like this?
So, I should use it like this, right?:
void CHttpsClient::converEncoding(CString& result, LPWSTR originalString, long encodingType)
{
if (encodingType == CP_ACP) {
return;
}
int nBufferSize = MultiByteToWideChar(encodingType, 0, (LPCCH)originalString, -1, NULL, 0);
wchar_t *pBuf = result.GetBuffer(nBufferSize * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)originalString, -1, pBuf, nBufferSize * sizeof(wchar_t));
}
void CHttpsClient::someMethod(){
CString text = _T("");
converEncoding(text, _T("Hello StackOverflow"), utf-8);
text.ReleaseBuffer();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.