Defined int parameter[NUM] returned segment fault
-
Hi all,
I'm having an issue with defining "int parameter[num]".
It success when compiling the code.
But If I run my application, it will show segment fault error to me when defining int parameter[num].if(DBG) { qDebug("DIDO_Light_on function in!"); } int result[DI_num]; if(DBG) { qDebug("result function defined!"); } int err_flag = false; QString get; //QStringList result; QStringList DI_get_value; QStringList DO_set_value_low; QStringList DO_set_value_high;
It crashes at
int result[DI_num];
What did I miss?
-
Please paste the code: your variable definition and exactly the line where it crashes.
-
@victor-wang
are you sureDI_num
is a positive value? If not than that's undefined behavior. -
@J.Hilk
Yes, I'm sure it is a positive value.
I defined it in mainwindow.h like below.private: int Comport_Count,LED_Light,PingIP_1,PingIP_2,a,b,height,width,can1_rec_prt,can0_send_prt,burn_chk,Burn_count,a_cpu,b_cpu,LanTabClick,DidoTabClick,dido_count; int count,active_test_item,test_result_count; int DI_num,DO_num,showconnectcount;
-
And it compiles? In C++ arrays cannot have dynamic sizes, what's between
[
and]
should be a constant expression. -
@victor-wang
yes, sinceC99
I believe.if you want a dynamically sized array, you should use
QVector<int>
yes, sincenope, had that wrong, variable length arrays are a C99 feature only.C99
I believe.
But C++ standard (till C++11) doesn’t support variable sized arrays. The C++11 standard mentions array size as a constant-expression.
However the GCC compiler seems to provide an extension to support them. -
@Devopia53
But DI_num would get a dynamic parameter form ini file.
I will convert String to int and give it to DI_num.So I should defined it like
int DI_num{1024};
first then give the new parameter to DI_num? -
This is possible if the value of the variable is set to an appropriate value before the array declaration is executed. But, I recommend using a vector.