wcscpy_s 报错Buffer is too small

"本文记录了一次在使用wcscpy_s时遇到的Buffer too small问题,重点在于理解wstring长度计算和''的重要性。通过修正代码示例,解释了为何需要额外加1,并提供了解决方法。"
摘要由CSDN通过智能技术生成

拷贝wchar_t*的时候,用到了wcscpy_s,本来很简单的代码,却出了Buffer is too small的问题,改了几次才好,这种低级错误在这里记录一下
原代码

wstring wstr = L"1234567890";//别处传来的字符串
wchar_t* ws = new wchar_t[wstr.length()];//这个长度有问题
memset(ws, 0, wstr.length()*sizeof(wchar_t));
wcscpy_s(ws, wstr.length(), wstr.c_str());
...
delete ws;//这里还会报错堆损坏
ws = NULL;

运行时会报错Buffer is too small,问题的原因是wcscpy_s的第二个参数问题,正确代码

wstring wstr = L"1234567890";//别处传来的字符串
wchar_t* ws = new wchar_t[wstr.length()+1];//要+1
memset(ws, 0, wstr.length()*sizeof(wchar_t));
wcscpy_s(ws, wstr.length()+1, wstr.c_str());//这里也要+1
...
delete[] ws;//wchar_t* delete和delete[]都能正确释放
ws = NULL;

背后的原理就是’\0’,wstring.length()和strlen/wcslen返回的长度都不带’\0’,所以要+1
msdn也给出了相应的说明

This value must be greater than zero and not greater than RSIZE_MAX. Ensure that this size accounts for the terminating NULL following the string.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值