itoa creates an infinite loop in C++

442 views Asked by At

This is very strange. itoa(); seems to create an infinite loop.

for(int i = 0; i < 10; i++)
{
        char buffer[1];
        itoa(i, buffer, 10);
        std::cout << buffer;
}

Why on earth does it do that? I've tried using different variables than i, numerical values without variables (i.e. itoa(1, buffer, 10);), it still keeps ending up in an infinite loop. I've tried to google without much success, I found an old mail about it here. I am using Windows XP 32 bit and Code::Blocks (with GCC) as a compiler.

Does anyone know what's wrong? Thanks in advance.

3

There are 3 answers

5
ildjarn On BEST ANSWER

itoa null-terminates the string it produces, but you haven't made buffer large enough to hold the terminating NUL character. Try:

for (int i = 0; i < 10; i++)
{
    char buffer[2];
    itoa(i, buffer, 10);
    std::cout << buffer;
}
1
Joe On

Your buffer is too small -- itoa will write a null-terminated string, so your buffer will need at a minimum 2 bytes to hold values from 0-9.

4
zwol On

Why on earth are you using a general number conversion routine for single digits?

for (int i = 0; i < 10; i++)
    std::cout << char('0' + i);

(You need the cast back to char so that the compiler uses the correct overload of <<. The C++ standard guarantees that the character constants '0' through '9' have consecutive numeric values.)