Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while trying to reverse a char array

Tags:

c

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!

like image 759
Matt M Avatar asked Jan 19 '26 15:01

Matt M


1 Answers

You are overindexing revBuffer. It is size 5, which means you can index it from 0 to 4, but the first index you use in it in your loop is 5.

like image 183
WhirlWind Avatar answered Jan 22 '26 07:01

WhirlWind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!