c - wcstombs 段错误

标签 c segmentation-fault core

这段代码

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/

相关文章:

C:没有显式返回构造的结构,但它仍然有效

c - 2 到 36 之间任意基数的大数的加法、减法和比较

c - C中二维数组的内存运行时错误

arrays - 带有导致段错误的指针的快速排序

python - 什么代表 Python 中 print/repr 上显示的十六进制整数?

linux程序没有回答。我怎么知道哪个例程导致了卡住?

c - 用 C 代码从 IPV4 迁移到 IPV6

c - C 中参数的顺序

c - UNIX shell 段错误

.net - 将GCP凭据添加到.net核心应用程序中的Docker