views:

36

answers:

2

Hello,

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(

Segmentation fault

Any ideas for the seg fault?

TIA, cateof

+3  A: 

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;
sharptooth
+2  A: 

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.

Timo Geusch