c++ - 使用 wmemset 初始化导致 coredump

标签 c++

我想将 int 值转换为 wchar_t buffer[MAX_LEN],使用 std::to_wstring(dwValue); 然后使用 res.copy 将值复制到缓冲区,我不知道为什么会导致 coredump。如果我删除 wmemset 行,一切顺利。

我使用 gdbvalgrind 并没有找到原因。这是 valgrind 结果:

==30757== Jump to the invalid address stated on the next line
==30757==    at 0x0: ???
==30757==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==30757== 
==30757== 
==30757== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==30757==  Bad permissions for mapped region at address 0x0
==30757==    at 0x0: ???
==30757== 
==30757== HEAP SUMMARY:
==30757==     in use at exit: 0 bytes in 0 blocks
==30757==   total heap usage: 1 allocs, 1 frees, 44 bytes allocated
==30757== 
==30757== All heap blocks were freed -- no leaks are possible
==30757== 
==30757== For counts of detected and suppressed errors, rerun with: -v
==30757== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault

我的代码如下:

/* intTowstring example */
#include <iostream>
#include <string>
#include <vector>
#include <cstdio> 
#include <cwchar>

std::wstring intToWstring( int dwValue )
{
    std::wstring str = L"";

    str = std::to_wstring(dwValue);
    return str;
}

int main ()
{

     wchar_t buffer[128];
     wmemset (buffer,L'\0',sizeof(wchar_t) * 128);

     int flags = 2048;

     std::wstring res = intToWstring(flags);
     res.copy(buffer,res.size(),0);

     wprintf(L"%ls\n",buffer);

     return 0; 
 }

最佳答案

wmemset (buffer,L'\0',sizeof(wchar_t) * 128);

我猜这是错误的。来自 wmemset documentation :

count - number of wide characters to fill

您提供的是字节数。更改为:

wmemset (buffer,L'\0',128);

关于c++ - 使用 wmemset 初始化导致 coredump,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54125904/

相关文章:

c++ - 如何在 C++ 中使用向上转换的 unique_ptr 指针仅引用在派生类中定义的方法?

c++ - 使用宏扩展作为标识符的一部分

c++ - 需要平面表示中数组索引的算法

c++ - 如何从 C++ 中的另一个类迭代获取数据?

作为另一个对象的一部分的对象的 C++ 构造函数

c++ - 是否可以从函数的循环中返回多个值? C++

c++ - 在 OpenCV 中流式传输视频

c++ - API 设计告诉 API 的使用者分配内存是最佳实践吗?

c++ - WinRT C++ : get package family name

c++ - 我正在使用 C++ 读写文件