Reputation: 33036
I am trying to converts a sequence of multibyte characters to a corresponding sequence of wide characters using the mbstowcs_s
function. But I keep having the following heap corruption problem. Can anyone tell me how to fix that?
Here is a sample code. When debugging, it is always the line delete wc_name
causing the problem. I know it shouldn't be it.
#include <Windows.h>
#include <iostream>
#include <string>
int main (int argc, char *argv[]) {
size_t returnValue; // The number of characters converted.
const size_t sizeInWords = 50; // The size of the wcstr buffer in words
const char* c_name = "nanana"; // The address of a sequence of characters
wchar_t *wc_name = new wchar_t(50);
errno_t err = mbstowcs_s(&returnValue, wc_name, sizeInWords,
c_name, strlen(c_name) );
wcout << wc_name << endl;
delete wc_name;
return 0;
}
Upvotes: 0
Views: 1417
Reputation: 73443
wchar_t *wc_name = new wchar_t(50);
should be wchar_t *wc_name = new wchar_t[50];
to allocate an array. And corresponding delete wc_name
should be delete[] wc_name;
. BTW, if you know the size of the array at compile time itself, there is no need for dynamic memory allocation. You can simply do wchar_t wc_name[50];
.
Upvotes: 5