简体   繁体   中英

Heap memory allocation crash with std::wstring

I have a big problem with std::wstring memory allocation. The program crash when I try to use this code:

size_t size;
mbstowcs_s(&size, NULL, 0, buffer, _TRUNCATE);
wchar_t *buffer2 = (wchar_t*)malloc(size + 1);
mbstowcs_s(&size, buffer, buffer_size, buffer, _TRUNCATE);
buffer2[size] = '\0';

std::wstring data(buffer);

the crash is on the last line and doesn't happen if I use the following line:

std::wstring data(L"hello");

the error is memory heap allocation failure and the result is the crash of the program. Why? What's wrong?

wchar_t *buffer2 = (wchar_t*)malloc((size + 1) * sizeof(wchar_t));
                                               ^^^^^^^^^^^^^^^^^

malloc allocates a number of bytes - you wan't a number of wchar_t 's

If you're using c++, the correct way is:

wchar_t *buffer2 = new wchar_t[size+1];

如果您使用std :: wstring我假设您使用的是C ++,请不要使用malloc,请使用new&delete(只是一个注释)

std::vector seems to be a good way to make a buffer here. Its constructor receives elements number (not bytes) and you don't have to remember to delete the memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM