wcstombs 分段错误
奇怪的是,这段代码编译时没有警告:
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(
分段错误
关于分段错误的原因有什么想法吗?
The strange thing is that this code compiles with no warnings:
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;
}
But when I run ./a.out it printed:
1
Characters converted: 40
Multibyte character: 1234(Segmentation fault
Any ideas about what causes the segmentation fault?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您会遇到缓冲区溢出,因为您在转换后没有以 null 终止缓冲区,并且缓冲区大小也不足以保存结果。
您可以动态分配内存,因为您事先不知道需要多少内存:
You encounter buffer overrun because you don't null-terminate the buffer after conversion and the buffer size is also not enough to hold the result.
You could allocate memory dynamically since you don't know in advance how much memory is required:
您正在尝试将一个肯定超过 4 个字符的字符串放入可容纳 4 个字符的字符数组中。由于您没有指定“4”作为最大大小,因此转换将写入它不拥有的内存或可能被其他变量使用的内存、堆栈上函数返回值等内部数据或类似数据。当您覆盖在调用 wcstombs 之前推送到堆栈上的数据(堆栈自上而下增长)时,这将导致段错误。
You're trying to put a string that's definitely longer than 4 chars into a char array that can hold 4 characters. As you don't specify '4' as the maximum size, the conversion will write into memory that it doesn't own or that might be used by other variables, house keeping data like function return values on the stack or similar. This will lead to the seg fault as you're overwriting data that was pushed on the stack (stacks grow top-down) before you called
wcstombs
.