I've a C++ code sample that I can't explain why it randomly causes the app to fail with either an access violation or heap corruption. I know the sample contains code that is currently frown upon (working directly with pointers to char), but this is just for learning purposes. If anyone could take a look over the code and let me know if you see something that I'm missing, I'd very much appreciate it. Thanks.
class Operand
{
private:
double value;
char* message;
public:
Operand(double value);
~Operand();
char* operator+(const Operand& other);
};
Operand::Operand(double value)
{
this->value = value;
}
char* Operand::operator+(const Operand& other)
{
char s[256];
double sum = this->value + other.value;
sprintf_s(s, "The sum of %f and %f is %f", this->value, other.value, sum);
this->message = new char[strlen(s)]; //this is where it sometimes crashes with an access violation
strcpy_s(this->message, sizeof(s), s);
return this->message;
}
Operand::~Operand()
{
if (this->message != nullptr)
delete[] this->message;
}
int main()
{
double operand1, operand2;
cout << "Please input the calculator parameters: operand1 operand2: ";
cin >> operand1 >> operand2;
auto Operand1 = Operand(operand1);
auto Operand2 = Operand(operand2);
char* message1 = Operand1 + Operand2;
char* message2 = Operand2 + Operand1;
cout << message1 << "\n";
cout << message2 << "\n";
return 0; //and sometimes it crashes right after outputting to cout
}
I don't see why the two char* message pointers would interfere with each other, since they belong to different Operand instances. If that is indeed the cause of it. Or maybe I'm missing something.
I'd really appreciate a second pair of eyes, as I'm out of ideas. Thanks.