I’m working on an assignment in which we are manipulating *.ppm images using a “Image” class. It compiles and then seg faults when the copy constructor is called. Here it is:
Image::Image(const Image & imageToCopy) {
fileType = imageToCopy.fileType;
width = imageToCopy.width;
height = imageToCopy.height;
maxColor = imageToCopy.maxColor;
image = new int *[height];
for(int i=0; i < height; i++) {
image[i] = new int [width];
for(int j=0; j < width; j++) {
image[i][j] = imageToCopy.image[i][j];
}
}
}
Called like so:
Image image2(image1);
I’m at somewhat of a loss for why this happens. I don’t know what is wrong because the code is almost identical to my constructor, which works fine. the only difference is that I have
image[i][j] = imageToCopy.image[i][j];
instead of
imageInputStream >> image[i][j];
Thoughts? Thanks
EDIT: Constructor is below:
Image::Image(const char* filename) {
ifstream imageInputStream;
imageInputStream.open(filename);
imageInputStream >> fileType;
imageInputStream >> width;
imageInputStream >> height;
imageInputStream >> maxColor;
image = new int *[height];
for(int i=0; i < height; i++) {
image[i] = new int [width];
for(int j=0; j < width; j++) {
imageInputStream >> image[i][j];
}
}
imageInputStream.close();
}
Without seeing the complete code, this is just a guess, but if you’ve created a copy constructor and a destructor but no copy assignment operator, you may get a segfault exactly like this if you try to use assignment.
And you may not think you’re doing an assignment anywhere, but unless you know all the rules of C++ (which even experts don’t, much less new students), it’s hard to be sure. The easiest way to find out is to declare a private assignment operator and don’t define it (or, if you’re using C++11, declare it deleted) and see if you get a compile error.
For example:
As the comment implies, if you uncomment the copy assignment operator, the whole thing works.
If this is your problem, read up on the Rule of Three (Wikipedia, Ward’s Wiki).