[英]wcstombs segmentation fault
此代碼
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,類別
您會遇到緩沖區溢出的情況,因為轉換后您不會對緩沖區進行空終止,並且緩沖區的大小也不足以保存結果。
您可以動態分配內存,因為您事先不知道需要多少內存:
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;
您正在嘗試將絕對長於4個字符的字符串放入可容納4個字符的char數組中。 由於您未將“ 4”指定為最大大小,因此該轉換將寫入它不擁有或可能被其他變量使用的內存,並在堆棧中保留諸如函數返回值之類的數據。 這將導致段錯誤,因為您將覆蓋在調用wcstombs
之前被壓入堆棧的數據(堆棧自上而下生長)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.