简体   繁体   中英

Declaration in for gives segmentation fault

I'm doing a homework for learning graphs. For that, I'm taking a csv file and I keep that information in a Sensor structure.

#define sensor_amount 70
typedef struct Sensor {
    int id;
    float x,y,z;
}Sensor; 

For getting this struct from file I'm using the following function:

Sensor* get_sensors(char* file_name){
    FILE* file = fopen(file_name,"r");
    //Skip first line
    char* c;
    fscanf(file,"%[^\n]",c);

    int id = 0;
    float x,y,z;

    Sensor* sensor_arr = malloc(sizeof(Sensor));
    fscanf(file,"%i,%f,%f,%f",&id,&x,&y,&z);
    sensor_arr[0].id = id;
    sensor_arr[0].x = x;
    sensor_arr[0].y = y;
    sensor_arr[0].z = z;

    int counter = 1;

    while(!feof(file)){
        fscanf(file,"%i,%f,%f,%f\n",&id,&x,&y,&z);
        ++counter;
        sensor_arr = realloc(sensor_arr,counter*sizeof(Sensor));
        sensor_arr[counter-1].id = id;
        sensor_arr[counter-1].x = x;
        sensor_arr[counter-1].y = y;
        sensor_arr[counter-1].z = z; 
    }
    fclose(file);
    return sensor_arr;
}

I'm calculating distances between each sensor with following code:

float** get_distances(Sensor* s){
    float** a = malloc(sensor_amount*sizeof(float*));

    for(int i = 0; i < sensor_amount;i++)
        a[i] = malloc(sensor_amount*sizeof(float));

    for(int i = 0; i < sensor_amount;i++){
        for(int j = 0; j < sensor_amount; j++){
            float dis = distance(s[i].x,s[i].y,s[j].x,s[j].y);
            a[i][j] = dis;
        }
    }
    return a;
}

Finally in my main i print those values like this:

int i,j;
int main(){
    char file_name[] = "sensor_locations.csv";
    Sensor* sensors; 
    sensors = get_sensors(file_name);
    float**ar=get_distances(sensors);
    for(i=0;i < 70; ++i)
        for(j=0;j<70;++j){
            printf("(%i,%i)->%f\n",i,j,ar[i][j]);
    }
    return 0;
}

In main, if I move the declarations of i and j to the for loops, it throws a segmentation fault. But why?

This is designed for array out of bounds bugs:

int counter = 1;
...
++counter;
...
[counter-1]

Instead do

for(int i=0; more_data; i++)
{
  sensor_arr[i] = ...;
  sensor_arr = realloc(sensor_arr,(i+2)*sizeof(Sensor));
}

Please note Why is “while (?feof (file) )” always wrong? .

And your use of realloc is wrong, use a tmp pointer for storing the result and check it against NULL before assigning it back to the sensor_arr pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM