Raikan 10
Raikan 10

Reputation: 115

Why does this code have a segmentation fault?

I find that that while running this code it says: Thread1:EXC_BAD_ACCESS(code=1,address=0x7fff3010efcc)

Code:

#include <iostream>
using namespace std;
int main()
{
int d[20],n,k,j,i,a[100000000],count=0;
//long long int i,a[100000000];
cin>>n>>k;
for(i=0;i<k;i++)
{
    cin>>d[i];
}
for(i=0;i<n;i++)
{
    a[i]=i;
}
for(i=0;i<n;i++)
{
    for(j=0;j<k;j++)
    {
        if(a[i]%d[j]==0)
        {
            a[i]=0;
        }
    }
}
for(i=0;i<n;i++)
{
    if(a[i]!=0)
    {
        count++;
    }
}
cout<<count;

}

Upvotes: 0

Views: 46

Answers (2)

AVK
AVK

Reputation: 2149

The stack has overflowed. There is no place for int a[100000000] as its size exceeds the default stack size (1MB on Windows)

Upvotes: 1

max66
max66

Reputation: 66200

If we don't know the values of n and k, we can't respond appropriately to your question.

By example, if you give the value 21 to k, you write (cin >> d[i]) d in position 20; this can cause the segmentation fault.

Suggestions:

1) run your program in a debugger

2) check the values for n and k

3) and use std::vector instead old C-style arrays and at() instead operator[] (by example: cin >> d.at(i), a.at(i) = i, etc. instead cin >> d[i], a[i] = i, etc.) because at() perform a bound checking.

Upvotes: 0

Related Questions