0

I am trying to make a copy constructor because I have a pointer in my class. However, I got runtime error "Debug Assertion failed" and I do not know what to do. I have two classses, MyMatrix and MyImage. I want to write a copy constructor for MyImage, therefore I also write one for MyMatrix.

class MyMatrix{
private:
unsigned _width, _height; 
unsigned char *_data;

public:
MyMatrix(MyMatrix &other);
}

MyMatrix::MyMatrix(MyMatrix &other) {
_width = other._width;
_height = other._height;
_data = new unsigned char[_width*_height];
memcpy(_data, other._data, _width*_height*sizeof(unsigned char));
}

class MyImage {
public:
int _width;
int _height;
MyMatrix _Y; //gray level
}

MyImage::MyImage(MyImage &other) {
_width = other._width;
_height = other._height;

_Y = MyMatrix(other._Y);
}

int main(){
    char *filename = "hw1_images/p1/house.raw"; //some raw image
    int width = 512;
int height = 512;

    //read the image
    MyImage inputImage(filename, width, height, fileMode::CFA);

    //copy the image 
    MyImage test(inputImage);
 return 0;
 }

I got error even if I comment the memcry(). If I use std::cout to display the value of my copy, it is alway 221. Please help me with it. Thank you.

HemHem
  • 45
  • 1
  • 4
  • 3
    This is not enough code for us to reproduce the error (and at first glance it looks correct). Could you give us a [minimal complete example](http://stackoverflow.com/help/mcve)? – Beta Sep 07 '15 at 03:45
  • Definitely would need a repro example. This could be an issue with the destructor, assignment operator (you have this, too - right?), memory corruption, a problem with the default constructor, or something else. – Michael Burr Sep 07 '15 at 03:50
  • If you used a vector, the default copy constructor and assignment operator would just work. Also your class wouldn't leak memory anymore.. let C++ work for you. – Neil Kirk Sep 07 '15 at 04:03

2 Answers2

0

If its just matter of crash then you may do something like below.

class MyMatrix{
private:
unsigned _width, _height; 
unsigned char *_data;

public:
    MyMatrix(){
    _width = 2;
    _height = 3;
    _data = new unsigned char[sizeof(unsigned char)];

}
MyMatrix(MyMatrix &other);
};

MyMatrix::MyMatrix(MyMatrix &other) {
_width = other._width;
_height = other._height;
_data = new unsigned char[(_width*_height) + 1];
memcpy(_data, other._data, _width*_height*sizeof(unsigned char));
}
Praveer Kumar
  • 514
  • 5
  • 16
0

You are writing _Y = MyMatrix(other._Y);, I expect that you have defined the assignement operator for your Matrix class : MyMatrix & operator(const MyMatrix & other); otherwise the compiler will create a default one for you that just copy your attributes, meaning your pointer will be copied, not the content.

And, as I see that you can manipulate an important size of data and if you have c++11 enabled, I would definitely look at the copy swap idiom : What is the copy-and-swap idiom?

Community
  • 1
  • 1
dkg
  • 1,745
  • 14
  • 32