1
#include <bits/stdc++.h>

using namespace std ;

int main () {
    int n ;
    cin >> n ;
    int a [n] ;

    for ( int i = 0 ; i < n ; i++ ) {
        cin >> a [i] ;
    }

    const int N = 1e6 + 2 ; // This is where the problem is...
    bool check [N] ;
    for ( int i = 0 ; i < N ; i++ ) {
        check [i] == 0 ;
    }

    for ( int i = 0 ; i < N ; i++ ) {
        if ( a [i] >= 0 ) {
            check [a[i]] = 1 ;
        }
    }

    int ans = -1 ;
    for ( int i = 0 ; i < N ; i++ ) {
        if ( check [i]==0 ) {
            ans = i ;
            break;
        }
    }

    cout << ans ;
    return 0 ;
}

When I run the above program in the VS Code terminal I get no output... :

PS C:\Users\LENOVO\Desktop\C++ Programs> cd "c:\Users\LENOVO\Desktop\C++ Programs\" ; if ($?) { g++ smallest_positive_missing_number.cpp -o smallest_positive_missing_number } ; if ($?) { .\smallest_positive_missing_number }
6
0 -9 1 3 -4 5
PS C:\Users\LENOVO\Desktop\C++ Programs> 
prapin
  • 6,395
  • 5
  • 26
  • 44
  • 1
    Start by stopping this: `int a[n];` and `bool check [N]`. Those are non-standard variable length array. It isn't portable, and is a recipe for blowing out your activation stack for any moderately large `n`, as you just found out. Use vectors instead. And fyi, there are other bugs. Ex: `check[i] == 0;` in your zero-fill initialization loop is wrong; it doesn't assign anything and your compiler will tell you as much if you bother to turn up your warnings and treat them as errors. – WhozCraig Dec 15 '21 at 11:15
  • 3
    `bool check [N] ;` with `N = 1e6 + 2` probably exceeds the stack size of the application. – Richard Critten Dec 15 '21 at 11:16

1 Answers1

-1

First, stop using VLA because it is NOT supported in c++ standard. Use vector or new instead.

int *a = new int[n];
bool *check = new bool[N];

And use them just like a normal array.
As for your problem, it is clearly caused by VLA with big size, and it will run perfectly once you switch to new or vector.
Edit:
However, like the comment below said, the array cited this problem is not VLA. They just act the same and mess up your stack.