为什么会出现分段错误?

时间:2015-11-23 00:33:22

标签: c segmentation-fault

为什么会出现分段错误?我正在调试它并将其缩小到switch语句中的大量分配,我该怎么做呢?

这是我的代码:

#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;
}

2 个答案:

答案 0 :(得分:1)

你写这样的东西:

masses[i].x = num;

但是之后:

int massesRead, i, num, partRead = 0;

你永远不会为i分配一个值,所以很可能它是一个比100更高的垃圾数量,因此你会超出阵列界限并获得你的段错误。

您遇到类似的问题,从不初始化massesRead,然后尝试massesRead++;

要修复,您可以更改为:

int massesRead = 0, i = 0, num, partRead = 0;

答案 1 :(得分:0)

很可能您为质量分配的元素多于您定义的元素。在读取例程中打印索引i并检查它是否> 100。