Destructor gives output I don't understand (Error in `./a.out': double free or corruption (fasttop):)

StackOverflow https://stackoverflow.com/questions/22327169

  •  12-06-2023
  •  | 
  •  

Question

We've been asked to write a class for matrices, and so far I have the following:

Code

But we're supposed to: "implement the following member functions: Parameterized constructor (utilizing new) and destructor (utilizing delete)"

And I'm not sure quite what that means but I think I've done that. The problem is when I uncomment line 65, I get a strange runtime error that I've not seen before. Any ideas about what I'm doing wrong? Thanks :)

Edit: Who voted my question down and why?

Also, I added:

        matrix(matrix &m) {
        // Copy size and declare new array
        mdata=0; size=(m.getcols()*m.getrows());
        if(size>0) {
            mdata=new double[size];
            // Copy values into new array
            for(int i=0;i<size;i++) {
                mdata[i] = m.mdata[i];
            }
        }
    }

and

delete [] mdata;

and the error has gone now, so thank you Ilya Kobelevskiy and aruisdante for your answers.

Was it helpful?

Solution

You did not implement a copy constructor, so default one is called when you return by value from multiplication function.

Default constructor simply copies members byte-wise, so you end up having two matrices containing mdata that is pointing to the same memory block. When destructor for second matrix is called, it is trying to free memory that was already freed, hence the error.

Of course, plus what other people pointed out about delete [].

In general, you should follow rule of three. Applied to your case, it would mean that if you do anything non-trivial in destructor, you should either explicitly implement assignment operator and copy constructor, or declare them private and not implement them to avoid automatic compiler generated ones and make class non-copyable.

OTHER TIPS

mdata is an array, when you delete it in destructor, you need to add []:

delete [] mdata;

When you delete an array, you need to use the delete[] operator rather than the delete one. Note that deleting an array via delete is actually undefined behavior, that just happens to be what your particular code combination and compiler seem to be doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top