0
votes

I'm writing a class which deals with polynomials of an arbitrary size, and when overloading the * operator I have a buffer overrun warning that I don't know how to deal with.

Polynomial Polynomial::operator*(const Polynomial& rhs) 
{
    int returnSize = (this->size + rhs.getSize()) - 1;
    int* returnArray = new int[returnSize];

    for (int i = 0; i < this->size; i++) 
    {
        for (int j = 0; j < rhs.getSize(); j++)
        {
            returnArray[i + j] = this->polynomial[i] * rhs.polynomial[j];
        }
    }
}

And I think that by the nature of the program that it isn't actually possible to get buffer overrun, but I don't understand it very well so I'm probably mistaken. The warning states:

C6386: Buffer Overrun whilst writing to 'returnArray': the writable size is 'returnSize*4' bytes, but'8' bytes might be written.

I'm also having this issue with the copy constructor.

Polynomial::Polynomial(const Polynomial& rhs)
{
    this->size = rhs.getSize();
    this->polynomial = new int[rhs.getSize()];

    for (int i = 0; i < rhs.getSize(); i++)
    {
        this->polynomial[i] = rhs.polynomial[i];
    }
}

I really hope this isn't a daft question, and thanks for your help!

1
In expression (this->size + rhs.getSize()) - 1; why do you subtract 1? And I think your indexing [i + j] is incorrect. - vahancho
To reduce your headaches, consider switching to std::vector<int> rather than new'ing up your own int [] every time. - Tanveer Badar
It's because the highest power in the new polynomial will be equal to the 2 highest powers in the multiplying polynomials added together. And since the highest power is stored in the last element of array (for example X^3 is stored in index 3), then I must minus 1 from the new size, otherwise I'm left with an array which is too big. For example, two cubics (size 4) multiplied together would need an array of size 7, where the X^6 is stored in the 6th index. - Swepps
While I know that std::vectors are certainly easier, I'm trying to achieve this without using them to try and understand C++ better. - Swepps
hmm. I would say focus on polynomials and don't fight the STL. Use vectors, separately write a resource management class to get an idea of how to do that in C++. Two separate concerns. - Tanveer Badar

1 Answers

0
votes

The warning is caused because the compiler doesn't know the value of returnSize at compile time, and assumes it may be less than 2. You can easily remove this warning by assigning space for at least two int values in your new call:

int* returnArray = new int[std::max(returnSize,2)]; // Need #include <algorithm> for std::max