Run time error

Oct 22, 2015 at 9:34pm
The below code crashes in the function 'Solution' at the statement

 
if( value == zero )


only when 'value' variable contains '1000000000' as input. For smaller values it works fine. It's data type is int so it should accommodate the above mentioned value. Can someone see what am i missing out here??

The task description is at the following link.
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
64
65

#include <iostream>
#include <vector>

using namespace std;

int solution(vector<int> &);

int main(int argc, char *argv[])
{
    vector <int> A = {1000000000};

    int result = solution(A);
    cout <<"Result is : " << result <<endl;

    return 0;
}

int solution(vector<int> &A)
{
    int value = 0;
    size_t counter = 0;
    int zero = 0;
    vector <int> myVector(A.size() + 1);

    cout<<"size of new array is : "<< myVector.size() <<endl;

    for(size_t j = 0; j< myVector.size(); ++j)
    {
        myVector[j] = 0;
    }
    cout<<"comes here 1 "<<endl;

    for(size_t i = 0; i< A.size();  ++i )
    {
        cout<<"comes here 2 "<<endl;

        value = A[i];
        cout<<"value is  "<<A[i]<<  endl;

        if( value == zero )
        {
            cout<<"comes here 3 "<<endl;
            return 0;
        }
        else if( myVector[A[i]] == 0 )
        {
            cout<<"comes here "<<endl;
            myVector[A[i]] = A[i];
            ++counter;
        }
    }
    cout<<"counter value is :"<< counter<<endl;

    if( counter ==  A.size() )
    {
        cout<<"comes"<<endl;
        return 1;
    }
    else
    {
        return 0;
    }

}


Oct 22, 2015 at 10:18pm
Learn to use a debugger to identify such things.

It crashes on else if( myVector[A[i]] == 0 )
i = 0
A[i] = 1000000000
myVector.size() = 2
Oct 23, 2015 at 9:11am
Thanks for that tip..I understand the issue now. I was trying to access the array element that was outside the scope of my declared array.
Oct 23, 2015 at 11:07am
Hi,



You should be clearer on your array inicalization ;-)

1
2
3
4
vector <int> A;
A.SetSize(1000000000);
for (int i = 0; i < 1000000000; i++)
    A[i] = 0;
Oct 23, 2015 at 1:45pm
Hello,
I did not want to make the array that big. I just wanted to check my code for a single member array with a big element value. It was failing at this case. For other cases the array could be big offcourse but '1000000000' was an element 'value' and not the size. Thanks for your response though.
Topic archived. No new replies allowed.