Search code examples
c++runtime-errorinfinite-loop

Can anyone figure out how this code showing running error? It is printing infinite time -1 along with correct answer


#include <iostream>
using namespace std;

int subarraysum(int arr[],int n,int sum){
    int cur_sum=0,start=0;
    for(int i=0;i<n;i++){

     cur_sum=cur_sum+arr[i];

    while(start<i && cur_sum>sum){
        cur_sum=cur_sum-arr[start];
        start++;
         }

    if(cur_sum==sum)
     {
         cout<<start<<" "<<i;
         return 1;
     }
    }
    cout<<"-1";
  //return 0;  
}
int main() {
    int t;
    cin>>t;
    for(int l=0;l<t;t++){
        int n,s;
    cin>>n>>s;
    int arr[n]={0};
    for(int i=0;i<n;i++)
    {cin>>arr[i];
    }

    subarraysum(arr, n, s);

    }
return 0;
}

This question is simple input output question but it is printing my answer and the infinite times -1 and i am not able to figure out the problem with this code and its running time error problem.


Solution

  • I think the problem here is indeed tricky. You declare a function int subarraysum(int arr[],int n,int sum). The problem here is the return statement. Your function must return a value, but your code does not, in this form. This leads to undefined behavior. The int main()-function in C++ is the only function in C++, which has a non-void-return value, that is allowed to not return anything.

    Depending on the optimization level of your compiler this undefined behavior can result in an endless loop, even though the for-loop before seams to exit. Try to uncomment return 0; at the end of the function, this should do the job.

    Btw. debugging your code will not help you here, because the behavior is different in debug-mode. There everything could be fine. Compile your code with all warnings on -Wall -Wextra -pedantic. The compiler will tell you that there could be a problem. Treat warnings like errors.