简体   繁体   中英

Getting Segmentation Fault error in C++ code

#include<bits/stdc++.h>
using namespace std;
//FIRST REPEATING ELEMENT (APPROACH 2)

int main()
{
    cout<<"running";
    int n;
    cin>>n;
    int arr[n];
    for(int i=1; i<=n; i++)
        cin>>arr[i];

    const int N = 1e5+2;
    int idx[N];

    for(int i=0;i<N;i++)
        idx[i] = -1;

    int minidx = INT_MAX;

    for(int 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"<<endl;
    else
        cout<<minidx + 1<<endl;

    return 0;

}

I am writing this code for "First Repeating Element" question and trying to get the index of the first element that repeats. On debugging, I am getting segmentation fault. int main() { (in this line)

What does it mean and what can I do to remove this.

const int N = 1e5+2;
int idx[N];

That sounds like a big array to be allocated on the stack (400kb!). Try using malloc() to allocate an array of that size. Change that to something like

const int N = 1e5+2;
int* idx = (int*)malloc(N * sizeof(int));

You should also do the same for arr , particularly if you use large values for n.

The program has undefined behavior because you're going out of bound of the array. This is because in your for loop condition, you're using i<=n instead of i<n .

Undefined behavior means anything 1 can happen including but not limited to the program giving your expected output. But never rely (or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.

Additionally, in Standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program.

int n;
cin >> n;
int arr[n]; //not standard C++ since n is not a constant expression

1 For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program .

Segmentation fault is due to usage of memory that you don't own, or in other words stack over flow. Most likely because you're creating an array of size 1e5+2 and looping over it, initializing every element. That's not the best way to find the recurrence of an element. Instead use a map with key value pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM