【问题标题】:wcstombs segmentation faultwcstombs 分段错误
【发布时间】:2011-01-17 19:22:58
【问题描述】:

这段代码

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, 分类

【问题讨论】:

    标签: c segmentation-fault core


    【解决方案1】:

    您遇到缓冲区溢出,因为您没有在转换后对缓冲区进行空终止,并且缓冲区大小也不足以容纳结果。

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

    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;
    

    【讨论】:

      【解决方案2】:

      您正在尝试将绝对长于 4 个字符的字符串放入可以容纳 4 个字符的 char 数组中。由于您没有将“4”指定为最大大小,因此转换将写入不属于它的内存或可能被其他变量使用的内存,将数据(如堆栈上的函数返回值或类似数据)保存起来。这将导致 seg 错误,因为您在调用 wcstombs 之前覆盖了推入堆栈的数据(堆栈自上而下增长)。

      【讨论】:

        猜你喜欢
        • 2011-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-01
        • 2014-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多