c - Possible memory issue or something else? -
i have been working on series of tasks involving structs, reading , writing bin files in c.
the struct definition is:
struct data{ unsigned int a; unsigned short b; short c; char d[8]; short e; int f; int g; short h; char i; char j; unsigned long k; char l; double m; float n; int o; char p; double q; }
my reading , printing program seems working fine, code is:
int main (int argc, char **argv){ // check correct number of args file *record = fopen(argv[1], "r") // more prelim checks struct data entry; /* if first field exists, task assumption other fields * must exist proper sizes. */ while(fread(&entry.a, sizeof entry.a, 1, record) > 0){ fread(&entry.b, sizeof entry.b, 1, record); // ... read fields 1 one fread(&entry.q, sizeof entry.q, 1, record); printf("%u, %d, %d, %s, %d, %d, %d, %d, %c, %lu, %hhx, %f, %f, %d, %d, %f", entry.a, entry.b, entry.c . . . entry.q); } }
this prints out input bin file without error (tested automatically against 15 files, tens of entries). simplest one, 1 entry,
however, when try store data can sorted, using following array, data starts off correctly, goes haywire far can see:
struct data *entries = null; int curentries = 100; int counter = 1; entries = (struct data *) malloc(curentries * sizeof(struct data)); while(fread(&entries[counter - 1].a, sizeof entries[counter - 1].a, 1, record) >0){ /* same reading, storing , printing above, increment counter */ }
since reading , printing parts same, other use of "counter" variable, problem here array memory, , need fix?
edit: solved. implementation correct, many of these comments formatting , use of variables extremely helpful. issue difference in format had code for.
Comments
Post a Comment