I have a function that creates a copy of const char* in wchar_t*
wchar_t* to_wchar(const char* line)
{
size_t line_length = strlen(line) + 1;
wchar_t* wchar_name_temp = new wchar_t[line_length];
size_t outSize;
mbstowcs_s(&outSize, wchar_name_temp, line_length, line, strlen(line));
wchar_t* wchar_name = wchar_name_temp;
delete[] wchar_name_temp;
return wchar_name;
}
But when I call it in the main function the problem that I get is that under a certain amount of symbols(44 for me), it assigns the address that was allocated on the heap in the 2nd line of the function despite creating a copy of that line in the stack
int main()
{
wchar_t* str = to_wchar("10010101010101010101010101010101010101010101"); //random line
return 0;
}
You haven't made any copies. You've assigned a pointer. That's what your code says, and that's what it does.
This deletes allocated memory and then immediately returns it, which is almost certainly incorrect. If you want to copy a heap-allocated C-style array like this, you'll need to do so explicitly, using a
forloop orstd::copy.But in this simple example, you should just return
wchar_name_tempand forget about deleting at all, since you're returning it to the caller anyway.