Matt M
Matt M

Reputation: 3779

Error while trying to reverse a char array

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!

Upvotes: 2

Views: 391

Answers (5)

Doug T.
Doug T.

Reputation: 65599

In addition to what others have said, It doesn't appear that a null terminator will be placed in the last character of revBuffer even after you fix all your indexing issues. You will need to be sure to do

revBuffer[strlen(buffer)] = '\0';

This is also frought with problems because it assumes that buffer is properly terminated :)

Upvotes: 2

JoeG
JoeG

Reputation: 13182

For a start, you're trying to use a buffer that's 5 characters long to store a 6 digit number.

Upvotes: 0

pmr
pmr

Reputation: 59811

While your excercise is helpful you should keep in mind that there also is:

std::reverse(buffer, buffer + 5);

Upvotes: 2

anon
anon

Reputation:

The number you are converting has six digits - the buffer you are using is only big enough to hold 4 plus a null terminator. Make the buffer bigger.

Upvotes: 6

WhirlWind
WhirlWind

Reputation: 14112

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.

Upvotes: 7

Related Questions