free() 调用中的 _snwprintf_s 堆损坏错误 [英] _snwprintf_s heap corruption error in free() call
问题描述
我正在尝试使用 _snwprintf_s 来连接两个字符串.我还想在每个字符串后附加 \r\n.
I am trying to use _snwprintf_s to concatenate two strings. I also want to append \r\n after each string.
所以我分配了一个 wchar 缓冲区,最初包括两个字符串的 \r\n 和 null.我试着一个接一个地打印.
So I allocate a wchar buffer initially including the \r\n and null for both strings. I try to print one after the other.
我看到两个字符串都被写入了.但是当尝试释放(wbuff)时,它会给我一个堆损坏"错误.我不知道我在哪里越界了.
I see both strings are written. But when trying to free(wbuff), it throws me a "Heap corruption" error. I am not able to figure where I am crossing the bounds.
我哪里出错了?让我知道.谢谢
Where am I going wrong? Let me know. Thanks
int main()
{
WCHAR* name1 = L"HelloWorld";
WCHAR* name2 = L"GoodMorning";
WCHAR* wbuff = NULL;
int i = wcslen(name1) + wcslen(name2) + 6; //in words for size of buffer
int out = 0;
wbuff = (WCHAR*)malloc(i * sizeof(WCHAR));
ZeroMemory(wbuff, i * sizeof(WCHAR));
int prevLen = 0, currLen = 0;
currLen = wcslen(name1) + 2; //in bytes
out = _snwprintf_s(wbuff,i,currLen, L"%s\r\n", name1);
printf("Wrote %d characters\n", out);
prevLen = currLen;
currLen = wcslen(name2) + 2;
out = _snwprintf_s((wbuff+prevLen),i,currLen, L"%s\r\n", name2);
printf("Wrote %d characters\n", out);
printf("%S of sisze %u", wbuff, wcslen(wbuff));
free(wbuff);
printf("memory freed\n");
}
推荐答案
_snwprintf_s
用 fefe
标记填充缓冲区中的剩余字符.我在文档中找不到这个,但我可以在调试器中看到它.因此,您的第二个 _snwprintf_s 表示它有 i
字符可用,但您的起始位置是 prevLen
个字符.修复 i
以进行偏移调整.
_snwprintf_s
fills up the remaining characters in the buffer with an fefe
marker. I can't find this in the documentation, but I can see it in the debugger. Hence, your second _snwprintf_s is indicating it's got i
characters available, but your start position is prevLen
chars into it. Fix i
to have the offset adjustment as well.
取而代之的是:
out = _snwprintf_s((wbuff+prevLen),i,currLen, L"%s\r\n", name2);
这个:
out = _snwprintf_s((wbuff+prevLen),i-prevLen,currLen, L"%s\r\n", name2);
_snwprintf_s
会用标记填满整个缓冲区
_snwprintf_s
will fill up the entire buffer with markers
取而代之的是:
printf("%S of sisze %u", wbuff, wcslen(wbuff));
这个:
printf("%ls of sisze %u", wbuff, (unsigned int)(wcslen(wbuff)));
这篇关于free() 调用中的 _snwprintf_s 堆损坏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!