Why segmentation fault (core dump)?

I've written the following code for http://uva.onlinejudge.org/external/114/11466.html

When i give 1234567 as input it shows segmentation fault (core dump)..why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>

#define M 1000000

using namespace std;

bool marked[M];

vector<int>p;
vector<int>q;

bool isPrime (long long n)
{
    if(n < 2) return false;
    for (long long i=2; i*i <= n; i++)
    {
        if (n % i == 0)
            return false;
    }

    return true;
}


void sieve (long long n)
{
    for (int i=2; i<=n; i++)
    {
        if (marked[i] == false)
        {
            p.push_back(i);

            for (int j = i+i; j<=n; j+=i)
                marked[j] = true;
        }
    }
    for(int k=0; k<p.size(); k++)
    {
        if(n%p[k]==0)
            q.push_back(p[k]);
    }
}

int main()
{
    long long n;

    while(scanf("%lld",&n) && n!=0)
    {
        sieve(n);

        if(isPrime(n)==true)
            printf("-1\n");
        else
            printf("%d\n",q[q.size()-1]);
    }

    return 0;
}
Segmentation fault is a memory error which means you've gone beyond the memory allocated to the program by the OS. In more concrete terms, you've gone far beyond the bounds of an array. This happens on line 32 for you.

At the start of your program, you declared marked to have M elements or 1,000,000. When you input 1,234,567, like 32 tries to access the 1237567th element. This goes significantly beyond the bounds of your array, causing your segmentation fault.
Topic archived. No new replies allowed.