Reputation:
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;
}
Upvotes: -1
Views: 258
Reputation: 1553
wchar_t* wchar_name_temp = new wchar_t[line_length];
// ...
wchar_t* wchar_name = wchar_name_temp;
delete[] wchar_name_temp;
return wchar_name;
First you allocate the wide string on the heap. wchar_name_temp
points to the memory which is storing it. Then you copy only the location of that wide string into wchar_name
. So both the pointers now point to the same memory and both live on the stack (no matter where they point). Only the wide string itself lives on the heap. When you then delete[]
the memory (which still both pointers point to), it gets deleted for both of them and you return a dangling pointer. Using this pointer is UB (undefined behavior).
Generally speaking you should avoid any pointers and manual allocations/deallocations in C++ and rather use some containers from the standard library. Using them your function could look like this:
std::wstring to_wchar(const std::string& line) {
std::wstring wstr(line.size(), L'\0');
wstr.resize(std::mbstowcs(wstr.data(), line.data(), line.size()));
return wstr;
}
Upvotes: 1
Reputation: 70257
despite creating a copy of that line in the stack
You haven't made any copies. You've assigned a pointer. That's what your code says, and that's what it does.
wchar_t* wchar_name = wchar_name_temp;
delete[] wchar_name_temp;
return wchar_name;
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 for
loop or std::copy
.
But in this simple example, you should just return wchar_name_temp
and forget about deleting at all, since you're returning it to the caller anyway.
Upvotes: 1