std::wstring 导致堆内存分配崩溃
我对 std::wstring 内存分配有一个大问题。当我尝试使用此代码时,程序崩溃:
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);
崩溃位于最后一行,如果我使用以下行,则不会发生:
std::wstring data(L"hello");
错误是内存堆分配失败,结果是程序崩溃。为什么?怎么了?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
malloc
分配多个字节 - 您不需要多个wchar_t
如果您使用的是 c++,正确的方法是:
malloc
allocates a number of bytes - you wan't a number ofwchar_t
'sIf you're using c++, the correct way is:
如果你使用 std::wstring 我假设你使用的是 C++,不要使用 malloc,使用 new &删除(只是旁注)
If you use std::wstring I assume you are using C++, dont use malloc, use new & delete (just a side note)
std::vector 似乎是在这里创建缓冲区的好方法。它的构造函数接收元素数(而不是字节),并且您不必记住删除内存。
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.