Search code examples
c++classpointersoperator-overloadingdynamic-memory-allocation

C++: pointer being freed was not allocated error when having an overloaded operator return a class


I'm trying to overload the + operator for a class I've created in CPP, but whenever I return the new class object defined in the overloading function it gives me the error:

a.out(48371,0x10374a600) malloc: *** error for object 0x7ff7bf6525a0: pointer being freed was not allocated
a.out(48371,0x10374a600) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

My class definition is this in the .h file for my program (with the necessary #includes and using statements at the top):

class Matrix{
    public:
        Matrix(int);
        Matrix();
        ~Matrix();
        int getLength();
        float* getData();
        void readMatrix(string fileName);
        Matrix operator + (Matrix &trixIn) {
            Matrix matrix;
            float out1[trixIn.getLength()];                       
            
            float* dataA = trixIn.getData();
            float* dataB = data;

            for (int i = 0; i < trixIn.getLength(); i++){                 
                out1[i] = dataA[i] + dataB[i];         
            }

            matrix.length = trixIn.getLength();
            matrix.data = out1;
            // all this data up this point is correct when printed to the terminal

            return matrix;   // returning this to the main function brings up the error
        }
        void print();
    private:
        float *data;
        int length;
};

This is the part of my main function that I'm trying to call (A and B are two other previously defined Matrix objects):

Matrix C = A + B;
cout << "A + B with overload" << endl;
C.print();

And this is the print() function being called in main():

void Matrix::print(){
    for (int i = 0; i < length; i++){
       cout << std::setw(8) << data[i];  
    }
    printf("\n");
}

It says that a pointer being freed was not allocated, but I'm not at all attempting to free any allocated data--what does this error mean and what is a good way of going about fixing the problem?

Apologies if the answer is obvious, I've only just switched from C to C++, and I never entirely got the hang of pointers and proper data allocation. Thank you for any and all advice!


Solution

  • The error is here

    float out1[trixIn.getLength()];
    ...
    matrix.data = out1;
    

    Firstly this is not even legal C++. In C++ array bounds must be constants, and trixIn.getLength() is not a constant. This construction is known as a variable length array or VLA, and some compilers accept it, but as I said, not legal C++, so on some compilers this code would not even compile. It is legal C however, which perhaps is why you are using it.

    Having said that this code is bugged even on a compiler that accepts it. The VLA out1 only exists in the operator + that you have written. Once that function is exited the array is destroyed. But you have stored a pointer to that array in data. Therefore your Matrix class is left with a pointer to an array which no longer exists, this is called a dangling pointer and that causes your crash. In C++ you can never ignore the lifetime of objects, it's very easy to write code that points to or references objects that no longer exist.

    The solution to both these issues is to use dynamic allocation

    float* out1 = new float[trixIn.getLength()]; 
    

    Because the memory is dynamically allocated it does not get destroyed when the function is exited and that particular problem is avoided.

    Now you may have many other problems (I haven't tested your code), and you definitely do have the problem of leaking memory (as you said you never free any memory). But I guess that issue is for the future.