itoa
needs array long enough to hold the whole value plus null character at the end.
In your case, you need to allocate at least 2 chars, otherwise the null character at the end falls on the unallocated memory.
See the documentation on itoa.
For the pure C, sprintf
should be a more portable solution:
char aVar[2];
sprintf(aVar, "%d", 2);
(as itoa
, according to the documentation, is not universally available).
If you are using C++, the better way of them is to use a stringstream. See this question: Alternative to itoa() for converting integer to string C++? for the discussion.