【发布时间】:2017-03-21 23:09:27
【问题描述】:
我有一个 C++ 代码示例,我无法解释为什么它会随机导致应用程序因访问冲突或堆损坏而失败。我知道该示例包含当前不受欢迎的代码(直接使用指向 char 的指针),但这仅用于学习目的。如果有人可以查看代码并让我知道您是否看到我遗漏的东西,我将非常感激。谢谢。
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
}
我不明白为什么这两个 char* 消息指针会相互干扰,因为它们属于不同的 Operand 实例。如果这确实是它的原因。或者也许我错过了什么。
我真的很感激第二双眼睛,因为我没有想法。谢谢。
【问题讨论】:
标签: c++