Vector memory reallocation
I use vector<pair<int,int> > ar[100000];
and I have to use it for multiple test cases where every time I want it to initialize but I get a segmentation error for that.
I tried this by declaring inside the test loop and globally. its working great for the first test case or if there is only one test case.
I also tried to remove a vector after each test case, but I don't know the exact syntax for removing 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;
}
source to share
vector<pair<long long,long long> > ar[n+9];
is illegal in C ++. The dimensions of a C-type array must be known at compile time.
If your compiler allows it, you must use a compiler extension that can cause your crashes. For example, perhaps it results in a stack overflow, although we are vastly superior to what the C ++ standards cover.
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 an exception bad_alloc
. (It might be helpful to add a handler catch
for this case).
You should also check that the 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 loop for(i=0;i<n;i++){
because it is i
used as an index in distance
. Actually hardcoding 10000
seems suspicious here.
Alternatively use ar.at(a-1)
instead of ar[a-1]
etc. will work to check boundaries.
source to share