-1

When I write the following three lines of code into the main function, the program will not run.

const int N = 500005;
long long a[N]={0};
long long b[N]={0};

At first, I thought it was a problem with "const", but I deleted "const" and it still couldn't run. When I put these three lines of code outside the main function and the program can run successfully, I don't know why. Here is the complete code:

using namespace std;
int main()
{
  const int N = 500005; 
  long long a[N]={0};
  long long b[N]={0};
  long long n,q;
  cin>>n>>q;
  for(long long i=1;i<=n;i++)
  {
    cin>>a[i];
    b[i]=a[i]-a[i-1];
  }
  while(q--)
  {
    long long l,r,x;
    cin>>l>>r>>x;
    b[l]+=x;
    b[r+1]-=x;
  }
  for(long long i=1;i<=n;i++)
  {
    b[i]+=b[i-1];
    if(b[i]<0)
    {
        cout<<"0"<<" ";
    }
    else
        cout<<b[i]<<" ";
  }

  return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Sophia912
  • 11
  • 1
  • 3
    An error message would be a nice addition to the question – Revolver_Ocelot Apr 04 '22 at 16:24
  • It won't run because the stack (automatic storage duration) typically is a very limited resource. Your arrays are too large for the stack. On msvc the default is 1MB of stack per thread even in 64 bit applications. – drescherjm Apr 04 '22 at 16:26
  • 1
    Get into the habit of using address sanitizer. It will tell you exactly where and what the memory issue is. See it for yourself here: https://godbolt.org/z/q7qK9zqba. Here is a tutorial on how to use address sanitizer: https://www.youtube.com/watch?v=hhpzDFvXopk – Ari Apr 04 '22 at 16:40

1 Answers1

0

Within main the arrays have automatic storage duration. Declared in the namespace scope the arrays have static storage duration that is reserved before the program will be run.

So the reason of the problem is that there is no enough memory used for automatic variable allocations for such big arrays.

Instead of the arrays you could use objects of the standard container std::vector<long long>.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335