Crash after MessageBox!!!

I was trying to make a simple ansi to unicode and vice versa conversation but i encounter problem but i don't know where should make the fix.

Here is the sample code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
wchar_t *AnsiToUnicode(char *strAnsi)
{
	wchar_t *uOutStr;
	int lenA = lstrlenA(strAnsi);
	int lenW = MultiByteToWideChar(CP_ACP, 0, strAnsi, lenA, NULL, 0);
	if (lenW > 0)
	{
		uOutStr = (wchar_t *)malloc(lenW + 1);
		MultiByteToWideChar(CP_ACP, 0, strAnsi, lenA, uOutStr, lenW);
		uOutStr[lenW] = 0;
		return uOutStr;
	}else{
		return NULL;
	} 
}

char *UnicodeToAnsi(wchar_t *strUnicode)
{
	char *aOutStr;
	int lenW = lstrlenW(strUnicode);
	int lenA = WideCharToMultiByte(CP_ACP, 0, strUnicode, lenW, 0, 0, NULL, NULL);
	if (lenA > 0)
	{
		aOutStr = (char *)malloc(lenA + 1);
		WideCharToMultiByte(CP_ACP, 0, strUnicode, lenW, aOutStr, lenA, NULL, NULL);
		return aOutStr;
	}else{
		return NULL;
	}
}

int main(int argc, char* argv[])
{
	MessageBoxW(NULL, AnsiToUnicode("Hello World!"), AnsiToUnicode("Testing 1, 2, 3..."),  MB_OK);
	MessageBoxA(NULL, UnicodeToAnsi(L"Hello World!"), UnicodeToAnsi(L"Testing 1, 2, 3..."),  MB_OK);
	return 0;
}


When i run the program, all things are working fine except it crash after the last message box.
So how do i fix this issue?

Thanks in advance :)
In AnsiToUnicode,
uOutStr = (wchar_t *)malloc(lenW + 1);
should be:
uOutStr = (wchar_t *)malloc(sizeof(wchar_t)*(lenW + 1));

In UnicodeToAnsi,
1
2
3
		aOutStr = (char *)malloc(lenA + 1);
		WideCharToMultiByte(CP_ACP, 0, strUnicode, lenW, aOutStr, lenA, NULL, NULL);
		return aOutStr;
should be:
1
2
3
4
		aOutStr = (char *)malloc(lenA + 1);
		WideCharToMultiByte(CP_ACP, 0, strUnicode, lenW, aOutStr, lenA, NULL, NULL);
		aOutStr[lenA] = 0;
		return aOutStr;


You have a buffer overrun in one function and not terminating the string in another, and finally, you leak the two strings at the end.
Thanks kbw, working fine now :)
Topic archived. No new replies allowed.