Mr PoopyButthole 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;

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: ");
g = (city*)malloc(n*sizeof(city));
printf("Input name: ");
printf("Input x: ");
printf("Input y: ");
int maxi,maxj;
double maxdistance;


if((distance(g[i],g[j]) < maxdistance) && (i!=j))
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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download