timeout: the monitored command dumped core - c++

i am running this code in online compiler showing dumped core error this program finding highest product of two pair.
#include <bits/stdc++.h>
using namespace std;
void maximumproductpair(int arr[],int n){
sort(arr,arr+n);
reverse(arr,arr+n);
int prod;
for(int i=0; i<n; i++){
cout<<arr[i];
}
prod=prod*arr[0];
prod=*arr[1];
cout<<prod;
}
int main()
{
int t,n;
int arr[n];
cin>>t;
cout<<"\n";
cin>>n;
cout<<"\n";
while(t--){
for(int i=0; i<n;i++){
cin>>arr[i];
}
}
maximumproductpair(arr,n);
return 0;
}
in code everything fine then why this error?

Mistake 1
The problem is that your t and n variables are uninitialized. This means both t and n have garbage value. And when you wrote:
int t,n;
int arr[n];//UNDEFINED BEHAVIOR because n has garbage value
You have undefined behavior because n has garbage value.
This is why it is advised that
always initialize built in types in local/block scope.
Mistake 2
Second, note that in C++ the size of an array must be a compile-time constant. So take for example the following code snippets:
int n = 10;
int array[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int array[n]; //CORRECT
Similarly,
int n;
cin >> n;
int array[n]; //INCORRECT becasue n is not a constant expression
Also note that some compilers provide compiler extension that lets you have variable length array. You can read more about it at Why aren't variable-length arrays part of the C++ standard?.
If you want to take the size of the array as input from the user then you should use dynamic sized containers like std::vector :
int n;
cin >>n;
std::vector<int> array(n);// CORRECT, this creates a vector of size n of elements of type int
Also see Why should I not #include <bits/stdc++.h>?.

Related

Segmentation fault(code dumped) in c++ after several try I cann't get the solution

#include <iostream>
using namespace std;
int main() {
int T,D;
long long int N;
long long int a[N];
long long int b[D];
cin>>T;
for(int i=0;i<T;i++)
{
cin>>N>>D;
for(int i=0;i<N;i++)
{
cin>>a[i];
}
for(int i=0;i<D;i++)
{
b[i]=a[i];
}
for(int i=0;i<(N-D);i++)
{
a[i]=a[i+D];
}
for(int i=0;i<D;i++)
{
a[i+N]=b[i];
}
for(int i=0;i<N;i++)
{
cout<<a[i];
}
cout <<endl;
}
return 0;
}
Why is this coding having segmentation fault? I have seen many solution but cann't get it right.On visual studio or any other application it is not working but on gfg it is working. Please help me solve this problem
There are several things that are wrong.
C-style arrays must be set at compile time. So if you want to use int a[N], N must to known at compile time. If you want a flexible array, one C++ way is to use std::vector.
Then the array a goes from 0 to N-1. So going a[N] is going too far. So a[i+N] is way out if bounds and will be segfault.
you declare array a with N element, but use index out of the array range.
long long int a[N]; // declare here, maximum element is N
for(int i=0;i<D;i++)
{
a[i+N]=b[i]; // use index out of array a
}

Why does my function always return 0 instead of returning the sum result?

I just started learning C++, now I'm making a simple array sum function.
Why is my code output always 0? Does it mean that my function returns "0"?
If I put cout in the function, it shows the right sum result.
#include <iostream>
using namespace std;
int ArraySum(int arr[], int size){
int sum=0;
for(int i=0 ; i<size; i++){
cin >> arr[i];
sum +=arr[i];
}
return sum;
}
int main()
{
int n, sum;
cin >>n;
int arr[n];
ArraySum(arr, n);
cout << sum;
return 0;
}
You are not assigning the return value to the sum when it is returned.
You have 2 options:
pass a pointer to the sum, and dereference it inside ArraySum()
assign the value that is returned by ArraySum() to the sum int.
You forgot to assign ArraySum()'s return value to main()'s sum. As a result, main()'s sum is still uninitialized when you print it.
Change this:
ArraySum(arr, n);
to this:
sum = ArraySum(arr, n);
As a side note, you should know that this is not actually valid, standard C++:
int arr[n];
This is a "variable-length array" ("VLA" for short.) This works on some C++ compilers because they support VLAs as an extension. But relying on compiler-specific extensions is not recommended if you want your code to be portable to any other C++ compiler.
Use std::vector instead. This also has the benefit of not needing to manually keep track of the size. vector knows its own size.
So, use this instead:
#include <iostream>
#include <vector>
// Note the '&' here. That means a reference of the vector is passed,
// not a copy, so the original vector defined in main() is used when
// assigning the values we read with `cin`.
int ArraySum(std::vector<int>& arr)
{
int sum = 0;
for (int i = 0; i < arr.size(); i++) {
std::cin >> arr[i];
sum += arr[i];
}
return sum;
}
int main()
{
int n;
int sum;
std::cin >> n;
std::vector<int> arr(n);
sum = ArraySum(arr);
std::cout << sum;
}
(Also note that there is no need to return 0 at the end of main(). It happens automatically. Keep in mind that this is only true for main(). No other function that returns a value is allowed to omit the return statement. main() is a special case in this regard. But it doesn't hurt to return 0 anyway though. It's up to preference.)

Reverse an Array but i'm getting a segmentation error

What am I doing wrong ???
It is giving me an error of segmentation fault .
I don't know what memory i'm accessing ??
#include <iostream>
using namespace std;
int main() {
int t;
int n;
int arr[n];
cin>>t;
cin>>n;
// taking array elements from user
for(int i=0; i<n;i++)
{
cin>>arr[i];
}
// reverse of the array
for(int i=n-1; i>=0;i--)
{
cout<<arr[i];
}
//code
return 0;
}
int n;
You've default initialised this variable. Thus, the value is indeterminate.
int arr[n];
Here, you use that indeterminate value. Thus, the behaviour of the program is undefined.
There are "data flow" languages where using a variable will stop execution waiting for you to initialise it later and continue. C++ isn't such language. You must initialise everything before using the value.
Besides that, n isn't a compile time constant expression. Because the size of the array variable isn't compile time conastant, the progarm is ill-formed in C++.
If you want an array to have a dynamic size, you can use dynamic storage. Simplest way to create a dynamic array is to use std::vector.
For starters you are trying to declare a variable length array
int n;
int arr[n];
Variable length arrays is not a standard C++ feature. Moreover you are using an uninitialized variable n as the size of the array.
Either declare the array with an expected maximum size or use standard container std::vector<int>. At least you should write provided that the compiler supports variable length arrays
int t;
int n = 1;
cin>>t;
cin>>n;
if ( n < 1 ) n = 1;
int arr[n];
//...
Also you are not reversing an array. You are trying to output an array in the reverse order.
To reverse an array you could use standard algorithm std::reverse or you can write an appropriate loop yourself as for example
for ( int i = 0; i < n / 2; i++ )
{
// or use std::swap( arr[i], arr[n-i-1] );
int tmp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = tmp;
}
and then you can output the reversed array.
You are not allowed to define array with Unknown size in C++ so int arr[n]; is Wrong! and if you have to use arrays and not know the size of it , you should use dynamic array with Pointers like this : int* a = new int[n] and also Deallocate Heap memory with Delete []array_name at end of your program and if it is possible for you not use arrays It's better for you use vectors because the size of it is dynamic.
look at this with vectors :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//by : Salar Ashgi
int main()
{
int k;
cout<<"Enter number of elements ?\n";
cin>>k;
vector<int> v;
cout<<"--------------------\n";
int x;
for(int i=0;i<k;i++)
{
cout<<"Enter num "<<i+1<<" : ";
cin>>x;
v.push_back(x);
}
reverse(v.begin(),v.end());//algorithm.h
cout<<"Reverse : \n";
for(int i=0;i<k;i++)
{
cout<<v[i]<<" ";
}
}

Accepted using Vectors but Rejected using Arrays in HELP BOB problem on CODECHEF C++

reference problem https://www.codechef.com/problems/HBOB02
here in this problem i solved it using below code but firstly i used arrays instead of vector but there i got wrong answer. why so ????
#include <bits/stdc++.h>
#define mod 1000000007
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n,k;
cin>>n>>k;
k=k-1;
vector<long long>arr(n); //if i use long long arr[n] here the solution is not accepted
for(long long i=0;i<n;i++)
{
cin>>arr[i];
}
vector<long long>ar(n); //also changing long long ar[n] here
ar[0]=arr[0];
for(long long i=1;i<n;i++)
{
ar[i]=arr[i]^arr[i-1];
}
long long cnt=0;
for(long long i=0;i<n;i++)
{
if(ar[i]&(1<<k))
cnt++;
}
cout<<cnt;
return 0;
}
Variable-length arrays are not part of the C++ standard, but some compilers provide them as an extension. If they get too large, the program breaks.
However, you don't even need to store all those numbers.
Since you're apparently into "competitive" programming, here is a solution that uses only a tiny fraction of your memory, and does one third as many loop iterations.
int main()
{
unsigned int n, k;
cin >> n >> k;
k -= 1;
int cnt = 0;
unsigned int last = 0;
for(int i = 0; i < n; i++)
{
unsigned int next;
cin >> next;
cnt += ((next^last) >> k) & 1;
last = next;
}
cout << cnt;
}
in>>n>>k;
vector<long long>arr(n); //if i use long long arr[n] here the solution is not accepted
The size of an array variable must be a compile time constant value in C++. For obvious reasons, a value read from user input at runtime is not a compile time constant value. As such, declaring the array suggested in the comment would make the program ill-formed.

Reverse of an array Hackerrank

This is a syntax of a program that I made of hackerrank to reverse an array. The location of the question is Practice < Data Structures < Arrays < Arrays - DS
the program seems to work fine on an online compiler but is showing error over hackerrank.
can anyone guide me where I went wrong?
#include<iostream>
using namespace std;
int main(){
int n,i;
int arr[n];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
You are creating an array with n elements before you read n, i.e n is having garbage value. Here is correct working code.
#include <iostream>
using namespace std;
int main(){
int n,i;
cout<<"Enter number of elements"<<endl; // Comment it if you don't want debug console outut
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements"<<endl; // Comment it if you don't want debug console outut
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
I changed your solution and it work fine now , i will tell you some notes for your future:
1 - You have to read size of array first before declare array as mentioned in comments by #HolyBlackCat , otherwise it will give garbage value.
2 - this command int arr[n]; won't work on all Compilers and may give you an Error. Is there a solution to declare array without specific size ? Yes , you can use Vector like that vector<int> arr(n);but you have to include library of vector first #include<vector>
3 - In C and C++ programs the main function is of type int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application. On most operating systems returning 0 is a success status like saying "The program worked fine". So you have to write return 0; in the end of your program.
#include<iostream>
#include<vector> // must include to use Vectors
using namespace std;
int main(){
int n;
cin >> n; // Must read size of array first , otherwise it will give it garbude value
vector<int> arr(n); // instead of int arr[n]
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
for(int i = n-1 ; i >= 0 ; i--)
cout << arr[i] << " ";
cout << endl; // to print new line as mentioned in the problem statement
return 0; // Prefer to use it always
}
Hope that helps you and Good Luck.
The exercise of Hacker Rank needs that you reverse an array of integers, might you have a problem with the variable size array, cause some compilers support this characteristic but others not.
And Hacker Rank do not support some properties in other languages like JS , Hacker Rank do not support prompt() for take an input.
In any case for fix this error you can use vector class.
#include<iostream>
#include<vector>//Include library vector for dynamic size of array
using namespace std;
int main(){
int n;
cin>>n;
vector<int> arr(n);//Declare the vector with a max size n
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i = n-1 ;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
This code has passed al test cases of hackerRank
All the test on hackerRank had passed