Amir Rachum
Amir Rachum

Reputation: 79615

C++ data changing with no apparent reason

I have the following method:

void Polygon::expand() {
    int newSize = max * 2;
    printArray(array, current);
    Point* newArray = new Point[newSize];
    printArray(array, current);
    for (int i = 0; i <= current; i++) {
            newArray[i] = array[i];
    }
    delete[] this->array;
    array = newArray;
    max = newSize;
}

printArray is for debugging and is also very simple:

void printArray(Point* array, int size) {
    cout << "array\n==========" << endl;
    for (int i=0; i<=size; i++) {
            cout << array[i] << ": " << array[i].getX() << ", " << array[i].getY() << endl;
    }
}

The method is trying to expand array, which is a class member of type Point*. The weird thing is the prints I get when running this:

array
==========
(0,0): 0, 0
(1,1): 1, 1
(2,2): 2, 2
(3,3): 3, 3
array
==========
(0,0): 0, 0
(1,1): 1, 1
(2,2): 2, 2
(3,5.58294e-322): 3, 5.58294e-322

For some reason the last Point in array changes, even though I haven't touched it between the prints! Any idea on what can cause that?

Upvotes: 1

Views: 74

Answers (1)

dirkgently
dirkgently

Reputation: 111130

When you start your indexing from 0 (as in C and C++) you stop at one less than the size. So, do:

for (int i=0; i<size; i++) // not <= 

This is a classic off-by-one error (and you're invoking UB).

Upvotes: 7

Related Questions