使用 wmemset 初始化导致核心转储

Use wmemset initialize cause coredump

本文关键字:核心 转储 wmemset 初始化 使用      更新时间:2023-10-16

我想将int值转换为wchar_t buffer[MAX_LEN],使用std::to_wstring(dwValue);然后使用res.copy将值复制到缓冲区,我不知道为什么会导致核心转储。如果我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'',sizeof(wchar_t) * 128);
     int flags = 2048;
     std::wstring res = intToWstring(flags);
     res.copy(buffer,res.size(),0);
     wprintf(L"%lsn",buffer);
     return 0; 
 }
wmemset (buffer,L'',sizeof(wchar_t) * 128);

我想这是错误的。从wmemset文档中:

count - 要填充的宽字符数

您正在提供多个字节。更改为:

wmemset (buffer,L'',128);
快速

浏览一下wmemset的文档就会发现,最后一个参数应该是元素的数量,而不是字节的数量。

引用文档:

wchar_t* wmemset( wchar_t* dest, wchar_t ch, std::size_t count );
Parameters
dest    -   pointer to the wide character array to fill
ch  -   fill wide character
count   -   number of wide characters to fill 

解决方案是将呼叫更改为wmemset wmemset (buffer,L'',128);

参考