0

I am writing a simple program on vscode. The code is producing an error called segmentation fault only in vscode. But the strange thing is that code is working perfectly fine on onlinegdb compiler.

 #include<iostream>
using namespace std;
int main()
{
  int n, i;
  const int N= 1e6 +2;
  cin>>n;
  int minidx = INT_MAX;//will have the index of the smallest number
  int arr[n];
  for(i =0 ; i< n; i++)
    cin>>arr[i];
  int idx[N];
  for(i =0 ; i< N; i++)
    idx[i] = -1;
  for (i =0; i<n; i++)
  {
    if(idx[arr[i]] != -1)
    {
      minidx = min (minidx, idx[arr[i]]);
    }
    else
    idx[arr[i]] = i;
  }
  if (minidx == INT_MAX)
  {
    cout<<"-1";
  }
  else 
    cout<<minidx + 1;
}
 
Botje
  • 26,269
  • 3
  • 31
  • 41
  • `int arr[n]` is not standard c++. Refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) which are also available as PDFs for free. – Jason Oct 14 '22 at 08:17
  • *"working perfectly fine..."* Undefined behavior is not perfectly fine. "Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash." – Jason Oct 14 '22 at 08:18
  • `int idx[N];` requires about 4MB of stack space. Perhaps your local compiler defaults to only 1MB? – BoP Oct 14 '22 at 08:20
  • In addition to preceding comments, it's also quite dangerous to do `idx[arr[i]]` where elements of `arr` are read from the user, since there is nothing to guarantee that `arr[i]` is a valid index for `idx`. To avoid such problems, your code needs to check the value of `arr[i]` BEFORE using it as an index. – Peter Oct 14 '22 at 11:54

0 Answers0