-1

I've used different values of n below and above 10^8. It works fine below it. But starts showing SIGSEGV once the input to n increases upto 10^8 or more. Why does this happen? My compiler is g++ 7.4.0

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    long long int n, k, c = 0;    
    
    cin >> n >> k;
    long long int arr[n];
    for(long long int i =1; i <=n ; i+=2){
        arr[c] = i;
        
        c++;
    }    
    
    for(long long int j =2; j <=n ; j+=2){
        arr[c] = j;
        
        c++;
    } 
    cout << arr[k-1];
    
    return 0;
}
underdog
  • 31
  • 4
  • 1
    `long long int arr[n];` is not valid C++. You may be relying on a VLA compiler extension. – Eljay Aug 21 '20 at 21:11
  • I'm amazed the program managed to live that long. Usually the stack maxes out at 1-10 MB. Making it to 800 MB without something going wrong enough to end the program is impressive. – user4581301 Aug 21 '20 at 21:26
  • Note: Add the `-pedantic` flag to the compiler command line to get a warning when you use non-standard options. Unless you're using them deliberately, pedantic can save you from a lot of embarrassment later. – user4581301 Aug 21 '20 at 21:28

1 Answers1

0

You're allocating a large array on the stack -- when it gets too large, the stack overflows and you get a SIGSEGV.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226