I keep getting an error of "Expression: crtlsvalidHeapPointer(block)"
When I run the program, it executes all the way to the end but it triggers this error.
I believe I created big three expression. making deep copying and deleting previous address.
Is there I am missing point of creating big three expression?
#include <iostream>
using namespace std;
//between 0 and 255
class color {
int *red, *green, *blue;
public:
color() {
red = new int; green = new int; blue = new int;
*red = 0; *green = 0; *blue = 0; }
color(int r, int g, int b) {
if (r < 0 || r>255)
r = 0;
if (g < 0 || g>255)
g = 0;
if (b < 0 || b>255)
b = 0;
red = new int;
green = new int;
blue = new int;
*red = r;
*green = g;
*blue = b;
}
color(const color &rhs) :red(new int), green(new int), blue(new int) { *this = rhs; }
color & operator=(const color &rhs) {
if (this == &rhs)
return *this;
delete red;
delete green;
delete blue;
red = rhs.red;
green = rhs.green;
blue = rhs.blue;
return *this;
}
~color() {
delete red;
delete green;
delete blue;
};
color & operator +(const color & rhs) {
int r, g, b;
r = *red + *rhs.red;
if (r > 255)
r = 255;
g = *green + *rhs.green;
if (g > 255)
g = 255;
b = *blue + *rhs.blue;
if (b > 255)
b = 255;
color *thecolor = new color(r, g, b);
return *thecolor;
}
color & operator /(const color &rhs) {
int r, g, b;
if (*red == 0 || *rhs.red == 0)
r = 0;
else
r = *red / (*rhs.red);
if (*green == 0 || *rhs.green == 0)
g = 0;
else
g = *green / (*rhs.green);
if (*blue == 0 || *rhs.blue == 0)
b = 0;
else
b = *blue / (*rhs.blue);
color *newcolor = new color(r, g, b);
return *newcolor;
}
int getred() const { return *red; }
int getgreen()const { return *green; }
int getblue() const { return *blue; }
void set_red(int r) { *red = r; }
void set_green(int g) { *green = g; }
void set_blue(int b) { *blue = b; }
friend ostream &operator <<(ostream &out, const color &c) {
out << "(" << c.getred() << ", " << c.getgreen() << ", " << c.getblue() << ")";
return out;
}
};
int main() {
color c1(100, 150, 220);
color c2(23, 100, 76);
color c3(c1);
color c4 = c2;
//testing << operator
cout << "c1: " << c1 << endl;
cout << "c2: " << c2 << endl;
cout << "c3: " << c3 << endl;
cout << "c4: " << c4 << endl;
cout << "testing + and / operators" << endl;
cout << "c1+c2: " << c1 + c2 << endl;
cout << "c1/c2: " << c1 / c2 << endl;
return 0;
}