After allocating memory for a wchar_t* parameter and copying a string into the buffer, when returning from the function the buffer can not be read. Per the debugger:
machineName 0xcccccccccccccccc wchar_t *
given the following code
wchar_t *machineName;
EXPECT_TRUE(c_GetMachineName(machineName));
file test.cpp
…
#include "sysCertStore.h"
TEST(sysCertStoreC, c_GetMachineName)
{
wchar_t *machineName;
EXPECT_TRUE(c_GetMachineName(machineName));
setlocale(LC_ALL, "");
printf("%ls", machineName);
free(machineName);
}
file sysCertStore.h
…
#ifdef __cplusplus
extern "C"
{
// only need to export C interface if
// used by C++ source code
BOOL c_GetMachineName(wchar_t* machineName);
};
#endif
file sysCertStore.cpp
…
BOOL c_GetMachineName(wchar_t* machineName) {
wchar_t Name[MAX_COMPUTERNAME_LENGTH + 1];
int i = 0;
LPWSTR infoBuf = new wchar_t[MAX_COMPUTERNAME_LENGTH + 1]; // = {''};
DWORD bufCharCount = MAX_COMPUTERNAME_LENGTH + 1;
memset(Name, 0, MAX_COMPUTERNAME_LENGTH + 1);
if (GetComputerNameW(infoBuf, &bufCharCount))
{
for (i = 0; i < MAX_COMPUTERNAME_LENGTH + 1; i++)
{
Name[i] = infoBuf[i];
}
delete[] infoBuf;
INT strln= wcslen(Name)+1;
machineName = (wchar_t*)malloc(strln * sizeof(wchar_t)); // new wchar_t[strln];
wcscpy_s(machineName, strln, Name);
return TRUE;
} else
{
wcscpy_s(Name,7+1, L"Unknown");
return FALSE;
}
return FALSE;
}
I’m expecting the test to print the machine name and free the memory of the allocated string/buffer, allocated in the c_GetMachineName function.
TEST(sysCertStoreC, c_GetMachineName)
{
wchar_t *machineName;
EXPECT_TRUE(c_GetMachineName(machineName));
setlocale(LC_ALL, "");
printf("%ls", machineName);
free(machineName);
}