[英]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. 当我通过程序调试时,出现了这个奇怪的错误(程序收到信号SIGSEGV,分段错误->指向下面的代码行)。 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.
我试图设置一些“ if”条件来处理构造函数和析构函数中的“负”初始化值。
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. all_2.array2[i]
为NULL[i]
因为您没有为负数初始化数组。
You forgot to initialize all_2.number2
to 0 in the constructor for negative inputs. 您忘记了在负输入的构造函数
all_2.number2
初始化为0。
The problem is that yyou do not initialize data member number2 if the first argument of the constructor is negative. 问题是,如果构造函数的第一个参数为负,则您不会初始化数据成员number2。 So number2 can hold any arbitrary value.
因此number2可以保存任意值。 This is the reason of the abend.
这就是中止的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.