0

What is segmentation fault???

Hi , please help me to find out the bug . I think my code generally works properly , but when I give it greater input , it shows me some error ... and that's " Segmentation fault " , what is it ?? https://code.sololearn.com/cHVo4U7c9IUj/?ref=app

1st Apr 2021, 4:21 AM
Ali_combination
Ali_combination - avatar
11 ответов
+ 5
First of all, variable length arrays (VLAs) are not a part of the C++ standard. Declaring a sized array using a variable is against the standard. Arrays should always be initialized with a constant. int arr[n]; // bad int arr[10]; // ok ``` constexpr size_t ARR_SIZE = 100; int arr[ARR_SIZE]; // ok ``` Regarding the segfault, as CarrieForle said, the array `b` is created when n=0. So an array of size 0 is created. Later in the code, you're accessing indices greater than the size of the array, hence the segmentation fault. Making a larger array is an option, but it's also a waste of space. Use std::vector instead. Here is the fixed code https://code.sololearn.com/cpJPi10U2aW7/?ref=app
1st Apr 2021, 5:25 AM
XXX
XXX - avatar
+ 4
Read here about segmentation faults: https://en.m.wikipedia.org/wiki/Segmentation_fault
1st Apr 2021, 5:29 AM
XXX
XXX - avatar
+ 4
This question looks like an attempt to solve a competitive programming problem, if that's the case then I would recommend using dynamic array ( or vectors from C++ stl ) over static arrays as generally the size limit of input that they give is huge and you would not want most of the stack memory allocated to your program to be filled with one single array.
1st Apr 2021, 6:01 AM
Arsenic
Arsenic - avatar
+ 2
Make b a larger array. Like b[50] b[100].
1st Apr 2021, 4:42 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
XXX thank you so much
1st Apr 2021, 8:52 AM
Ali_combination
Ali_combination - avatar
0
Can you tell me what your program was supposed to do first? cause I'm not getting what it is. It would also help if you can provide input examples, ones that worked out fine, and ones that triggers the error.
1st Apr 2021, 4:33 AM
Ipang
0
Ipang i-th number one from right , shows 2^(i-1) . This code shows sum of a number as powers of 2 .
1st Apr 2021, 4:42 AM
Ali_combination
Ali_combination - avatar
0
CarrieForle thank you , how can I make a program with a bettet performance?
1st Apr 2021, 4:43 AM
Ali_combination
Ali_combination - avatar
0
CarrieForle hmmm..that error is caused of size of the array?
1st Apr 2021, 4:44 AM
Ali_combination
Ali_combination - avatar
0
Sorry, didn't get what you mean by "i-th number". Are you referring to i-th bit of a binary value? Is the input number a decimal value to be converted to binary? if so, then where is input of bit index?
1st Apr 2021, 4:46 AM
Ipang
0
Yeah , you are right...i-th bit shows 2^(i-1).
1st Apr 2021, 4:47 AM
Ali_combination
Ali_combination - avatar