Help with Runtime Error in my Code

I am getting a runtime error (SIGSEGV) on my code and I don’t know how to fix it. Please help. Thanks.


My Solution:

My Code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>

using namespace std;
typedef pair<int, int> Coord;
bool second_descend(const pair<int, int>& i, const pair<int, int>& j) {
	if (i.second < j.second) return false;
	if (j.second < i.second) return true;
	return j.first < i.first;

float get_distance(Coord a, Coord b){
	return sqrt(pow(b.first - a.first, 2) + pow(b.second - a.second , 2));

int main() {

	int t, n;
	Coord coordinate_template;
	cin >> t;

	while (t--){
		vector<Coord> points;
		cin >> n;
		while (n--){
			cin >> coordinate_template.first >> coordinate_template.second;
		sort(points.begin(), points.end());

		for (int a = 0; a < points.size()-2; a++){

			if (points[a].first == points[a + 1].first){
				int counter = a + 1;

				while (points[counter].first == points[a].first){

				sort(points.begin() + a, points.begin() + counter, second_descend);


		float sum = 0;
		for (int a = 0; a < points.size()-1; a++){
			sum += get_distance(points[a], points[a + 1]);
		cout << floor(sum * 100 + 0.5) / 100 << endl;
 	return 0;

You counter variable brings the RTE here.

 int counter = a + 1;

            while (points[counter].first == points[a].first){

The memory located outside vector contains some garbage values but by coincidence if the memory location just outside vector and last index of vector contains same value counter will be increased to a value greater than the size of the vector. then sort function used here gives RTE.

                sort(points.begin() + a, points.begin() + counter, second_descend);

You must limit the counter to vector size so while loop must be

while (counter < points.size() && points[counter].first == points[a].first){

The above correction is just to avoid RTE Im not sure about the correctness of your code

1 Like

Had a very brief look at your code.
But I think

 while (points[counter].first == points[a].first)

should be

while (counter < points.size() && points[counter].first == points[a].first)

Sorry about the weird formatting of the code in the post. I am new to the forum.