Search code examples
c++access-violationitoa

Unexpected Acess violation (itoa)


In K&R book, there is itoa code in Chapter 3 on 64th page. I tried to compile the code, but i was not successful. Here is the code:

#include <iostream>
#include <conio.h>
using namespace std;
void itoa(int, char*);

int main(void) {
    _getch();
    char arr[100];
    itoa(-18,arr);
    _getch();
    return 0;
}

void itoa(int n, char* s) {
    int i, sign;
    if ((sign = n) < 0) {
        n = -n;
    }
    i = 0;
    do {
        s[i++] = n % 10 + '0';
    } while ((n / 10) > 0);
    if (sign < 0) s[i++] = '-';
    s[i] = 0;
    //reverse(s);
}

Output:

Access violation on line 25, which is: s[i++] = n % 10 + '0';


Solution

  • itoa has an endless loop that exceeds the bounds of arr after 100 digits are generated. The loop is not modifying n so it can terminate when n reaches 0. Change the while condition to use n /= 10 instead of n / 10.