I'm trying to get better at C++ (I know a little). I'm working on character arrays. I found an exercise where the objective is to reverse a character array (after I convert it from an integer). I'm getting the following error (using VS2005):
Run-Time Check Failure #2 - Stack around the variable 'revBuffer' was corrupted.
When I step through the code, I notice the following:
revBuffer = 0x0012fe40 "100899ÌÌÌÌÌÌÌÌÌÌ998001"
The relevant code is below.
char buffer[5];
char revBuffer[5];
int i;
int j=5;
long number = 998001;
itoa(number, buffer, 10);
for(i=0; i<strlen(buffer);i++)
{
revBuffer[j] = buffer[i];
j--;
}
Any help would be great. TIA!
strlen(buffer)out of theforloop expression, so that it doesn't get computed needlessly in every loop.strlenworks by scanning the entire string until it sees the null terminator. I think that leavingstrlenin the loop would be a form of "premature pessimization" (IMHO).cnotc++, I retagged appropriately. The C++ code would be usingstd::stringand.at()which would have indicated theout_of_rangeissue.copy_backward, notat(). End of discussion ;-)