whishky
whishky

Reputation: 416

reallocating memory of a vector

I am using vector<pair<int,int> > ar[100000]; and I have to use it for several test cases where every time I want it to initialize but I am getting segmentation fault for this.

I tried it with declaring inside the test case loop and globally. its running fine for the first test case or if there is only one test case.

I also tried to delete the vector after every test case but I don't know the exact syntax of deleting a vector of this type, any help ??

int main() {
    long long a, b, c, d = 0, i, j, n, m, t; 
    scanf("%lld", &t);
    while (t--) {
        scanf("%lld %lld", &n, &m);

        vector<pair<long long, long long> > ar[n + 9];
        for(i = 0; i < m; i++) {
            scanf("%lld %lld %lld",&a,&b,&c);
            ar[a - 1].push_back(make_pair(b - 1, c));
            ar[b - 1].push_back(make_pair(a - 1, c));
        }
        vector<long long> distance(10000, 100000000); 
        scanf("%lld", &a); 
        dijkstra(ar, a - 1, distance); 

        for (i = 0; i < n; i++) {
            if (i == a - 1)
                continue;
            if (distance[i] != 100000000)
                printf("%lld ", distance[i]);
            else {
                // printf("%lld\n", visited[i]);
                printf("-1 ");
            }
        }
        printf("\n");
        // ar.clear();
        distance.clear();
    }
    return 0;
}

Upvotes: 3

Views: 109

Answers (1)

M.M
M.M

Reputation: 141638

vector<pair<long long,long long> > ar[n+9]; is illegal in C++. C-style array dimensions must be known at compile-time.

If your compiler allows this you must be using a compiler extension, which could be leading to your crashes. For example possibly this causes a stack overflow, although we are well beyond what is covered by C++ standards.

Instead of using a C-style array, use a vector:

vector<vector<pair<long long,long long>>> ar(n+9);

Then it is legal, and if you run out of memory you will get a bad_alloc exception thrown. (Adding a catch handler for this case might be useful).

You should also check that array indices are not out of bounds before using them. For example:

scanf("%lld %lld %lld",&a,&b,&c);
if ( a < 1 || a > ar.size() || b < 1 || b > ar.size() )
   throw std::runtime_error("Edge out of bounds");

Also you should check n < 10000 before entering the for(i=0;i<n;i++){ loop, because i is used as an index into distance. In fact hard-coding 10000 seems suspicious here.

Alternatively, using ar.at(a-1) instead of ar[a-1], etc., would work to do the bounds checking.

Upvotes: 2

Related Questions