简体   繁体   English

wcstombs分割错误

[英]wcstombs segmentation fault

this code 此代码

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;
}

and the strange thing is that it compiles with no warnings. 奇怪的是它编译时没有警告。

when I run ./a.out it printed 1 Characters converted: 40 Multibyte character: 1234( 当我运行./a.out时,它打印了1个已转换的字符:40个多字节字符:1234(

Segmentation fault 分段故障

Any ideas for the seg fault? 关于段错误的任何想法?

TIA, cateof TIA,类别

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: 您可以动态分配内存,因为您事先不知道需要多少内存:

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;

You're trying to put a string that's definitely longer than 4 chars into a char array that can hold 4 characters. 您正在尝试将绝对长于4个字符的字符串放入可容纳4个字符的char数组中。 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. 由于您未将“ 4”指定为最大大小,因此该转换将写入它不拥有或可能被其他变量使用的内存,并在堆栈中保留诸如函数返回值之类的数据。 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 . 这将导致段错误,因为您将覆盖在调用wcstombs之前被压入堆栈的数据(堆栈自上而下生长)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM