Reputation: 19
Why is this throwing a segmentation fault? I am debugging it and have narrowed it down to the assignment of the masses in the switch statement, how am I supposed to go about doing that instead?
Here is my code:
#include <stdio.h>
#define MAX 100
struct cg {
int x, y, mass;
};
struct cg masses[MAX];
int numberOfEntries;
int readin(void) {
FILE *file;
int massesRead, i, num, partRead = 0;
file = fopen( "WeightData.txt", "r" );
if( file == NULL ) {
printf( "Error: can't open file.\n" );
return 1;
} else {
while( fscanf( file, "%d", &num ) > 0) {
switch(partRead){
case 0:
masses[i].x = num;
partRead++;
continue;
case 1:
masses[i].y = num;
partRead++;
continue;
case 2:
masses[i].mass = num;
massesRead++;
partRead = 0;
i++;
continue;
}
}
}
fclose( file );
numberOfEntries = massesRead;
return massesRead;
}
void computecg(int n_masses) {
int sum_of_xmass;
int sum_of_ymass;
int sum_of_mass;
for(int i=0; i< numberOfEntries; i++){
sum_of_xmass += (masses[i].x * masses[i].mass);
sum_of_ymass += (masses[i].y * masses[i].mass);
sum_of_mass += (masses[i].mass);
}
int cg_x = sum_of_xmass / sum_of_mass;
int cg_y = sum_of_ymass / sum_of_mass;
printf("X = %d Y = %d.",cg_x, cg_y);
}
int main() {
int number;
if((number = readin()) > 0){
computecg(number);
}
return numberOfEntries;
}
Upvotes: 0
Views: 76
Reputation: 25936
You write things like this:
masses[i].x = num;
but after:
int massesRead, i, num, partRead = 0;
you never assign a value to i
, so most likely it is some huge garbage number that is way higher than 100
, hence you go way out of bounds on your array and get your segfault.
You have a similar problem with never initializing massesRead
, and then trying to do massesRead++;
To fix, you can change to:
int massesRead = 0, i = 0, num, partRead = 0;
Upvotes: 1
Reputation: 507
Very likely you assign more elements to masses than you defined. Print out your index i in the read routine and check, if it goes >100.
Upvotes: 0