riverhare
riverhare

Reputation: 35

C++ pointers: stack for an array was corrupted

The problem I want to solve with next code is to rotate the integer array of some size to a certain number shift. For instance, for

int a[5] = {1,2,3,4,5}

where size =5, for shift = 2 the result must be

{3,4,5,1,2}

This is my function

void rotate(int a[], int size, int shift)
{
    for (int i = 0; i < shift%size; ++i) {
        int *buffer = &a[0];
        a = &a[1];
        int l = *buffer;
        a[size - 1] = l;
    }
}

The output is right, but there is a runtime exception

Stack around the variable 'a' was corrupted

The problem is definitely in

a[size - 1] = l;

but I can't understand, what exactly is wrong.
Thanks in advance for your help.

Upvotes: 2

Views: 90

Answers (2)

Fabian
Fabian

Reputation: 66

As Bathsheba already has stated, a = &a[1]; (which has exactly the same effect as ++a; or a++;) moves the pointer with the effect that the assignment a[size - 1] = l; writes to the memory right next to the array. It depends on the code from which rotate is being called whether or not an error occurs. I have just run rotate together with a suitable main without error message (neither during compilation nor at runtime).

But rotate impossibly produces the right output. It does not at all rotate anything, but simply writes parts of the array into memory right next to the array. Is just seems as if there were something rotated, when there is sufficient free memory right to the array (otherwise the data there is overwritten) and when you change the startadress of the array also in the code which calls rotate.

To better understand what the program does, I have replaced some statements with such with exactly the same effect:

void rotate(int a[], int size, int shift) {
    for (int i = 0; i < shift%size; ++i) {
        // buffer was superfluous
        ++a;
        // l was superfluous
        a[size - 1] = a[-1];
    }
}

The following also has exactly the same effect as your program:

void rotate(int a[], int size, int shift) {
    for (int i = 0; i < shift%size; ++i) {
        a[size + i] = a[i];
    }
}

Now you can easily see, that the algorithm has to be changed in order to work as demanded.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234635

a = &a[1]; is shifting the pointer a by 1.

So a[-1] to a[3] inclusive are now the range of valid indices: a[size - 1] violates that.

I'd advise against changing a in this way.

Upvotes: 6

Related Questions