Mr PoopyButthole -4 years ago 46
C Question

# C program works (and gives correct output) but crashes anyway

The program calculates the distances between inputted cities on
cartesian coordinate system and outputs the closest 2 cities.

The program compiles without an issue so it must be a logical error but crashes as soon as the distance between the last 2 cities is too big (bigger than the distance between others).

When i wrote a printf inside the if statement near the end, it only showed that the if has been accessed once which can't be since if you input 3 cities i and j should be different 6/9 combinations.

``````#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct{
char name[16];
int x;
int y;
}city;

double distance(city a,city b)
{
double d;
d = sqrt((b.x-a.x)*(b.x-a.x) +(b.y-a.y)*(b.y-a.y));
return d;
}

int main()
{
int n,i,j;
city *g;
printf("Input number of cities: ");
scanf("%d",&n);
g = (city*)malloc(n*sizeof(city));
for(i=0;i<n;i++)
{
printf("Input name: ");
scanf("%s",g[i].name);
printf("Input x: ");
scanf("%d",&g[i].x);
printf("Input y: ");
scanf("%d",&g[i].y);
}
int maxi,maxj;
double maxdistance;

maxdistance=distance(g[0],g[1]);
for(i=0;i<n;i++){
//printf("i:%d\n",i);
for(j=0;j<n;j++)
{
//printf("j:%d\n",j);

{
if((distance(g[i],g[j]) < maxdistance) && (i!=j))
{
printf("debugcheck");
maxdistance = distance(g[i],g[j]);
maxi = i;
maxj = j;
}
}

}

}
printf("Least distance is %lf between %s and %s",distance(g[maxi],g[maxj]),g[maxi].name,g[maxj].name);
}
``````

The actual crash might come from the fact you forgot to initialize `maxi` and `maxj` before using them. Since the condition in the loop is not necessarily encountered, you should set them to 0 and 1 when you initialize `maxdistance`.