2

I'm trying to convert the digit's 0 to 9 to ASCII using _itoa_s and I find myself running into stack corruption errors using MSVC2012.

I thought that the ASCII table only occupied one byte per character, but from the looks of things, one byte isn't enough.

Where is my thinking wrong?

for (int digit = 0; digit < 10; digit++)
{
  char ch_digit;
  _itoa_s(digit, &ch_digit, 1, 10); 
}

I thought this simple loop should succeed, however it fails. I'm baffled.

Charles
  • 50,943
  • 13
  • 104
  • 142
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

2 Answers2

3

_itoa_s() should write out one char AND the terminating NUL char. You want it to write into a buffer with length = 1. So either you get the corruption error because of uninitialized ch_digit, or _itoa_s() is not _s (secure) and shmashes your stack by writing behind that one char.

But why not just calculating the ASCII char for base 10 'by hand' instead of using this non portable, MS specific lumber ?

for (int digit = 0; digit < 10; digit++)
{
    char ch_digit = '0' + digit; //'0' == 48 == 0x30
}
Sam
  • 7,778
  • 1
  • 23
  • 49
  • Actually, I edited it away. The NULL terminator would cause `_itoa_s()` to do nothing, leaving ch_digit uninitialized (fixed). – Sam Feb 03 '13 at 14:11
  • The null-terminator (or better zero-terminator) is the `NUL` character (equal to decimal `0`). There is no "*... NULL char*". `NULL` is a pointer value and something completly different. – alk Feb 03 '13 at 14:32
  • Yes, you'd go with null character, without abbreviation, would you? I'm sorry, if that caused serious confusion :) – Sam Feb 03 '13 at 14:40
2

itoa_* writes a string, so there's a null-terminator involved.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680