Search code examples
c++operator-overloadingcopy-constructorostream

c++ polynomial copy-constructor and ostream override cause memeory leaks?!


Hi there I am working on a polynomial class in c++. So far everything works very well. But now I encountered an error I simply cannot spot :/

polynomial.cpp

// copy-constructor
    Polynomial::Polynomial(const Polynomial &p){
        size = p.size;
        buffer = p.buffer;
        poly = new double(buffer);

        for (int i = 0; i < size; ++i) poly[i] = p[i];
        for (int i = size; i < buffer; ++i) poly[i] = 0;
    }

// output stream override | it's a non-member function
ostream& operator<<(ostream& os, const v1::Polynomial& p){      
    int degree = p.degree();
    stringstream ss;

    if (degree == 0) ss << '0';
    else if (degree > 0){
        ss << '(';
        for (int i = degree; i >= 0; --i){
            ss << p[i];
            ss << "x^";
            ss << i;
            if (i > 0)
                ss << " + ";
        }
        ss << ')' << endl;

    }
    os << ss.str();
    return os;
}

So this is how I call the copy-constructor:

// note: printing 'a' itself does not cause problems...
v1::Polynomial b(a);    
cout << "Polynomial b: " << b << " degree: " << b.degree() << endl;;

The stack-log from Visual Studio says it's in Line 23 (here: the line above this one, where I actually want to print 'b') and then it continues to call some heap functions etc.. Running the program without debug (via cmd) results in an APPCRASH, with "Polynomial b: " being the last thing displayed.

I unfortunately don't know how to debug in Visual Studio, I was used to valgrind in linux, which i currently don't have set up :/

Anyone any idea? Or do you need additional info?

Regardless, many thanks in advance =)


Solution

  • poly = new double(buffer);
    

    Here you allocate a single double and set it to buffer. You probably mean

    poly = new double[buffer];
    

    or whatever size you desire.

    A much better solution would be using std::vector instead of raw arrays. You can copy it with =, resize it with std::vector::resize and reserve more space with std::vector::reserve.