c - fread into array of structs segmentation fault -
i've been working on code awhile , i've run seg fault can't seem debug. here's relevant code:
typedef struct halo* halo; struct halo { float x, y, z; float vx, vy, vz; int n200a; float m200a; float r200a; int n200c; float m200c; float r200c; int n500a; float m500a; float r500a; int n500c; float m500c; float r500c; };
global variable:
halo *halo_catalog;
the function fails:
int loadhalocatalog(char *filename) { file *catalog_file; long long halo_num; catalog_file = fopen(filename, "rb"); if (catalog_file == null) { printf("could not open halo catalog: %s\n", filename); return -1; } if (fread(&halo_num, sizeof(long long), 1, catalog_file) < 0) { printf("could not read number of halos\n"); return -1; } halo_catalog = (halo *)calloc(halo_num, sizeof(struct halo)); if (fread(halo_catalog, sizeof(struct halo), halo_num, catalog_file) < 0) { printf("could not read number of halos\n"); return -1; } printf("%f\n", halo_catalog[10000]->x); printf("done\n"); fclose(catalog_file); return (int)halo_num; }
it fails on "printf("%f\n", halo_catalog[10000]->x);" line, or other access memory allocated after fread call. know passing in valid file, can read halo_num correctly. collects correct halo objects fread call, when call fread , check return returns halo_num.
thanks!
typedef struct halo* halo;
that's terrible idea, , cause of problems.
you have global variable
halo *halo_catalog;
so struct halo**
. in
halo_catalog = (halo *)calloc(halo_num, sizeof(struct halo)); if (fread(halo_catalog, sizeof(struct halo), halo_num, catalog_file) < 0) {
you use if struct halo*
.
then index
printf("%f\n", halo_catalog[10000]->x);
at distance of 10000 * sizeof(struct halo*)
bytes halo_catalog
points, , interpret bytes @ location - part of values of float
s or int
s read in, not pointers - , try access x
component of whatever arbitrary location result of misinterpretation.
you should
typedef struct halo halo;
and use halo_catalog[10000].x
fix issue.
another issue fread
returns number of items has read, if smaller requested number, can still positive number.
capture return value of fread
, , use determine whether reading successful. also, sure 10000 valid index before trying print halo_catalog[10000].x
.
Comments
Post a Comment