gpt4 book ai didi

c - wcstombs 段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:09:41 26 4
gpt4 key购买 nike

这段代码

int
main (void)
{
int i;
char pmbbuf[4];

wchar_t *pwchello = L"1234567890123456789012345678901234567890";

i = wcstombs (pmbbuf, pwchello, wcslen(pwchello)* MB_CUR_MAX + 1);

printf("%d\n", MB_CUR_MAX);
printf (" Characters converted: %u\n", i);
printf (" Multibyte character: %s\n\n", pmbbuf);

return 0;
}

奇怪的是它编译时没有警告。

当我运行 ./a.out 时它打印出来1个 字符转换:40 多字节字符:1234(

段错误

对段错误有什么想法吗?

TIA,类别

最佳答案

您遇到缓冲区溢出是因为您没有在转换后以 null 终止缓冲区,而且缓冲区大小也不足以保存结果。

您可以动态分配内存,因为您事先不知道需要多少内存:

int i;
char pmbbuf*;
wchar_t *pwchello = L"1234567890123456789012345678901234567890";
// this will not write anything, but return the number of bytes in the result
i = wcstombs (0, pwchello, wcslen(pwchello)* MB_CUR_MAX + 1);
//allocate memory - +1 byte for the trailing null, checking for null pointer returned omitted (though needed)
pmbbuf = malloc( i + 1 );
i = wcstombs (pmbbuf, pwchello, wcslen(pwchello)* MB_CUR_MAX + 1);
//put the trailing null
pmbbuf[i] = 0;
//whatever you want to do with the string - print, e-mail, fax, etc.
// don't forget to free memory
free( pmbbuf );
//defensive - to avoid misuse of the pointer
pmbbuf = 0;

关于c - wcstombs 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2279955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com