简体   繁体   中英

Program received signal SIGSEGV, Segmentation fault in output

I've been getting this weird error (Program received signal SIGSEGV, Segmentation fault -> that points to the line of code below) as I debug through the program. Please, really need your help in this. I'm trying to set up some "if" conditions that handles "negative" initialisation values in the constructor as well as destructor.

class a
{
public:
    a(int _number1=0, float* _array1=NULL);
    ~a();
    friend ostream& operator<<(ostream& output1, a& all_1);
private:
    int number1;
    float* array1;
};

class b
{
public:
    b(int _number2=0, float* _array2=NULL);
    ~b();
    friend ostream& operator<<(ostream& output2, b& all_2);
private:
    int number2;
    float* array2;
};

a::a(int _number1, float* _array1)
{
    if(_number1>0)
    {
        number1 = _number1;
        array1 = new float[number1];
        memset(array1, 0, number1*sizeof(float));
    }
    else array1=_array1;
}

a::~a()
{
    if(number1>0) delete[] array1;
}

ostream& operator<<(ostream& output1, a& all_1)
{
    if(all_1.number1>0)
    {
        for(int i=0;i<all_1.number1;i++) output1<<all_1.array1[i]<<"\n";
    }
    else output1<<"";
    return(output1);
}

b::b(int _number2, float* _array2)
{
    if(_number2>0)
    {
        number2 = _number2;
        array2 = new float[number2];
        memset(array2, 0, number2*sizeof(float));
    }
    else array2=_array2;
}

b::~b()
{
    if(number2>0) delete[] array2;
}

ostream& operator<<(ostream& output2, b& all_2)
{
    if(all_2.number2>0)
    {
        for(int i=0;i<all_2.number2;i++) output2<<all_2.array2[i]<<"\n"; //This is where the error appeared.
    }
    else output2<<"";
    return(output2);
}

int main()
{
    a input1(-1);
    b input_1(-1);
    cout<<input1;
    cout<<input_1;
}

all_2.array2[i] is NULL[i] because you didn't initialize the array for negative numbers.

You forgot to initialize all_2.number2 to 0 in the constructor for negative inputs.

The problem is that yyou do not initialize data member number2 if the first argument of the constructor is negative. So number2 can hold any arbitrary value. This is the reason of the abend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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