문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top