I am unable to find the proper reason for my program segmentation fault ,I don't Know the input also, in which it is getting segmentation fault, because I am submitting it to an online judge.
Please only you guys can help me ,may be you can tell the error by seeing it once.
I am new to programming.Help me ...
I was trying to solve very basic problem
https://www.spoj.com/problems/CANDY/
This is the one of most solved problem on spoj
I am getting a segmentation fault when submitting the below solution.
But in Visual Studio its working fine.
I also declared variables by considering the size (sum as long long int)
because it can be large
1) Is it due to the fact that I am declaring the array inside the while loop;
should I declare that array outside of while loop so that for every test cases it uses that same array
2) Is every time loop runs(for every test cases) the new array is created, will it lead to garbage collection or compiler will automatically free the memory after every test cases (I know about dynamic memory allocation in that case we have to free memory explicitly ) can you tell me in which scope I
should declare the variables?
3)If we declare a fresh array(s) for each iteration of while loop will it lead to the garbage until main remains on the stack ?
I got above doubts because segmentation fault is regarding memory access.
What I have tried:
#include<iostream>
using namespace std;
int main(){
while(1){
int n;
int arr[10001];
cin>>n;
if(n==-1)
break;
long long int sum=0;
for(int i=0;i<n;i++){
int temp;
cin>>temp;
sum+=temp;
arr[i]=temp;
}
int mean=sum/n;
if((sum%n)!=0){
cout<<-1<<endl;
continue;
}
int count1=0;
for(int i=0;i<n;i++){
if(arr[i]>mean){
count1+=(arr[i]-mean);
}
}
cout<<count1<<endl;
}
}