【问题标题】:Destructor crashing program with arrays c++带有数组c ++的析构函数崩溃程序
【发布时间】:2021-07-16 07:16:06
【问题描述】:

我正在学习 cpp,我尝试始终正确分配内存,但现在在添加解构函数后,它会因 HEAP CORRUPTION DETECTED 而崩溃。 我希望能够使 W1 小于 W2。现在,如果 W1 大于 W2,程序可以工作(没有 c 的析构函数),否则它将结果削减到 W1 的大小。 我使用 Visual Studio 2019。 这是我的代码:

#include <iostream>

using namespace std;
class Polynomial
{
private:
    int degree_; 
    int* ptr= nullptr;
public:
    Polynomial()
    {
        int* ptr = new int[1];
        ptr[0] = 0;
    }
    Polynomial(int degree)
    {
        degree_ = degree;
        ptr = new int[degree_ + 1]; //+1 for the coefficient next to x^0

    }
    Polynomial(const Polynomial& oldobj)
    {
        degree_ = oldobj.degree_;
        ptr = new int[degree_ + 1];
        *this = oldobj;
        //for (int i = 0; i < degree + 1; i++)
            //ptr[i] = oldobj.ptr[i];

    }
    ~Polynomial()
    {
        delete[]ptr;
    }
    Polynomial& operator+(const Polynomial& tempobj)
    {
        for (int i = 0; i <= tempobj.degree_; i++)
        {
            ptr[i] += tempobj.ptr[i];
        }

        return *this;
    }
    Polynomial& operator=(const Polynomial& tempobj)
    {
        degree_ = tempobj.degree_;
        ptr = tempobj.ptr;

        return *this;
    }
    friend istream& operator>>(istream& in, Polynomial& obj);
    friend ostream& operator<<(ostream& oou, const Polynomial& obj);
};

istream& operator>>(istream& in, Polynomial& obj)
{
    for (int i = obj.degree_; i >= 0; i--)
    {
        if (i == 0)
        {
            cout << "Last Coefficient: ";
            cin >> obj.ptr[i];
            break;
        }
        cout << "Coefficient in x^" << i << ": ";
        cin >> obj.ptr[i];

    }
    return in;
}
ostream& operator<<(ostream& out, const Polynomial& obj)
{
    cout << "f(x)= ";
    for (int i = obj.degree_; i >= 0; i--)
    {
        cout << obj.ptr[i] << "x^" << i << " ";
    }

    return out;
}
int main()
{
    Polynomial W1(2), W2(4), W3; //I want W1 to be able to swap places with W2.
                              //Right now it works only when W2 is smaller than W1;
    cin >> W1;
    cout << endl << W1<<endl;
    cin >> W2;
    cout << endl << W2 << endl;
    W3 = W1 + W2;
    cout << endl << W3;
    return 0;
}

首先,我该如何修复析构函数? 感谢您的宝贵时间。

【问题讨论】:

  • 检查您的operator+ 逻辑。如果tempobj 的度数大于this 对象的度数会怎样?
  • 更糟糕的是,当 default 构造函数被实际使用时,成员 degree_ 的值是多少?您的赋值运算符是 (a) 泄漏内存和 (b) 对现在共享的指针进行双重删除的秘诀。
  • 您的 operator= 也有问题,因为您将相同的指针分配给两个不同的多项式。当第一个析构函数被调用时一切都会好起来,但是当第二个析构函数被调用时,多项式将尝试释放一部分已经被释放的内存,因此你的堆损坏。
  • @TheUndeadFish 哦,这是编辑后的代码,我在其中删除了 operator+ 中的 if/else 部分,看看它是否有帮助。这就是它的样子: if(degree_ tempobj.degree_)
  • 你最好只使用矢量。

标签: c++ destructor heap-memory polynomials


【解决方案1】:

你的析构函数很好。 问题是您的加号运算符。 您需要创建一个能够存储所有系数的数组并返回对象的副本。 目前你改变你的第一个操作数。 还有其他问题,但不在这个问题范围内。

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 2014-12-15
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2014-03-16
    • 2011-06-12
    • 2018-07-01
    • 2018-01-03
    相关资源
    最近更新 更多