简体   繁体   English

如何解决程序崩溃的问题?

[英]How can I fix my program from crashing in C++?

I'm very new to programming and I am trying to write a program that adds and subtracts polynomials. 我对编程非常陌生,我正在尝试编写一个可增加和减少多项式的程序。 My program sometimes works, but most of the time, it randomly crashes and I have no idea why. 我的程序有时可以工作,但是大多数时候它会随机崩溃,我也不知道为什么。 It's very buggy and has other problems I'm trying to fix, but I am unable to really get any further coding done since it crashes. 这是非常多的错误,并且还有其他我要解决的问题,但是由于崩溃,我无法真正完成任何进一步的编码。 I'm completely new here but any help would be greatly appreciated. 我是这里的新手,但任何帮助将不胜感激。

Here's the code: 这是代码:

#include <iostream>
#include <cstdlib>

using namespace std;

int getChoice();
class Polynomial10
{
private:
    double* coef;
    int degreePoly;

public:
    Polynomial10(int max); //Constructor for a new Polynomial10
    int getDegree(){return degreePoly;};
    void print(); //Print the polynomial in standard form
    void read(); //Read a polynomial from the user
    void add(const Polynomial10& pol); //Add a polynomial
    void multc(double factor); //Multiply the poly by scalar
    void subtract(const Polynomial10& pol); //Subtract polynom
};

void Polynomial10::read()
{
    cout << "Enter degree of a polynom between 1 and 10 : ";
    cin >> degreePoly;

    cout << "Enter space separated coefficients starting from highest degree" << endl;
    for (int i = 0; i <= degreePoly; i++) cin >> coef[i];
}

void Polynomial10::print()
{
    for (int i = 0;i <= degreePoly; i++) {
       if (coef[i] == 0) cout << "";
       else if (i >= 0) {
           if (coef[i] > 0 && i != 0) cout<<"+";
           if ((coef[i] != 1 && coef[i] != -1) || i == degreePoly) cout << coef[i];
           if ((coef[i] != 1 && coef[i] != -1) && i != degreePoly ) cout << "*";
           if (i != degreePoly && coef[i] == -1) cout << "-";
           if (i != degreePoly) cout << "x";
           if ((degreePoly - i) != 1 && i != degreePoly) {
               cout << "^";
               cout << degreePoly-i;
           }
       }
   }
}

void Polynomial10::add(const Polynomial10& pol)
{
    for(int i = 0; i<degreePoly; i++) {
        int degree = degreePoly;
        coef[degreePoly-i] += pol.coef[degreePoly-(i+1)];
    }
}

void Polynomial10::subtract(const Polynomial10& pol)
{
    for(int i = 0; i<degreePoly; i++) {
        coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)];
    }
}

void Polynomial10::multc(double factor)
{
    //int degreePoly=0;
    //double coef[degreePoly];
    cout << "Enter the scalar multiplier : ";
    cin >> factor;
    for(int i = 0; i<degreePoly; i++) coef[i] *= factor;
}

Polynomial10::Polynomial10(int max)
{
    degreePoly = max;
    coef = new double[degreePoly];
    for(int i; i < degreePoly; i++) coef[i] = 0;
}

int main()
{
    int choice;
    Polynomial10 p1(1),p2(1);
    cout << endl << "CGS 2421: The Polynomial10 Class" << endl << endl << endl;
    cout
        << "0. Quit\n"
        << "1. Enter polynomial\n"
        << "2. Print polynomial\n"
        << "3. Add another polynomial\n"
        << "4. Subtract another polynomial\n"
        << "5. Multiply by scalar\n\n";

    int choiceFirst = getChoice();
    if (choiceFirst != 1) {
        cout << "Enter a Polynomial first!";
    }
    if (choiceFirst == 1) {choiceFirst = choice;}

    while(choice != 0) {
        switch(choice) {
            case 0:
                return 0;
            case 1:
                p1.read();
                break;
            case 2:
                p1.print();
                break;
            case 3:
                p2.read();
                p1.add(p2);
                cout << "Updated Polynomial: ";
                p1.print();
                break;
            case 4:
                p2.read();
                p1.subtract(p2);
                cout << "Updated Polynomial: ";
                p1.print();
                break;
            case 5:
                p1.multc(10);
                cout << "Updated Polynomial: ";
                p1.print();
                break;
        }
        choice = getChoice();
    }
    return 0;
}

int getChoice()
{
    int c;
    cout << "\nEnter your choice : ";
    cin >> c;
    return c;
}

When you create your objects with p1(1) and p2(1) the coef array in each object is allocated to contain one element. 当使用p1(1)p2(1)创建对象时,每个对象中的coef数组都被分配为包含一个元素。 Then in read() you simply set degreePoly to a (possibly higher) value but don't change the allocation of coef . 然后,在read()您只需将degreePoly设置为一个(可能更高)的值,但不更改coef的分配。 It will still contain only one element, but all coefficients are written to it, probably writing over the bounds of the array. 它仍然只包含一个元素,但是所有系数都写入其中,可能覆盖了数组的边界。 Instead the old coef should be freed and a new array of suitable size be allocated. 取而代之的是应该释放旧的coef并分配一个新的适当大小的数组。

Also in add and subtract you are assigning to coefficients out of bounds (for i=0): 同样在addsubtract您正在分配系数超出范围(对于i = 0):

coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)];

It also seems wrong mathematically to subtract the coefficients at index degreePoly-(i+1) from those at index degreePoly-i . 从索引度degreePoly-i的系数中减去索引度degreePoly-(i+1)的系数在数学上似乎也是错误的。 Additionally the case that the two polygons might have different degrees is currently not handled. 另外,当前不处理两个多边形可能具有不同程度的情况。

One issue is the coef allocation. 一个问题是coef分配。 You're allocating an array of degreePoly = max elements (1 for the two actual objects). 您正在分配一个由degreePoly = max元素组成的数组(两个实际对象为1)。 But I think it should be max + 1 , since a n-degree polynomial has n + 1 coefficients. 但我认为它应该为max + 1 ,因为n次多项式具有n +1个系数。 This off-by-one error appears elsewhere (eg add and mult). 这种一一对应的错误出现在其他位置(例如,加和多)。 Also in the constructor, you are not initializing i , so it has an undefined value, which alone means you can (probably will) write to memory you don't control. 同样在构造函数中,您没有初始化i ,因此它具有未定义的值,这仅意味着您可以(可能会)写入不受控制的内存。

Later, in your read code, you overwrite degreePoly , but do not reallocate coef , so it could be the wrong size, at least if you exceed your maximum. 稍后,在读取的代码中,您将覆盖degreePoly ,但是不要重新分配coef ,因此它的大小可能是错误的,至少在超出最大值的情况下。 Also note that you are accepting degreePoly + 1 coefficients (which I think is correct) here. 另外请注意,您在这里接受的degreePoly + 1系数(我认为是正确的)。 This means a max of 1 in the constructor only corresponds to a degreePoly of 0 in read! 这意味着构造函数中的max 1仅对应于read中的degreePoly为0! Entering 1 in read will cause two values to be read, which will overflow the array. read输入1将导致read两个值,这将使数组溢出。

Writing to invalid pointer locations and using uninitialized values causes undefined behavior, which is why it crashes sometimes . 写入无效的指针位置并使用未初始化的值会导致未定义的行为,这就是有时崩溃的原因。

if (choiceFirst == 1) {choiceFirst = choice;}

doesn't make sense since choice is not initialized at this stage. 这是没有意义的,因为choice没有在此阶段初始化。 You probably want: 您可能想要:

if (choiceFirst == 1) {choice = choiceFirst;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM