c - Why does realloc() crash my program? -
i trying resize array dynamically through use of realloc
. array initialized outside of function using malloc
.
here's function:
size_t verarbeite_anlagendatei(anlage *anlage_arr) { file *fp; anlage anlage; fp = fopen("anlagen.dat", "r"); if(fp == null) { printf("anlagedatei existiert nicht. bitte mit menuepunkt (0) weiter machen.\n"); return 0; } int index = 0; size_t size = 1; while(fscanf(fp, "%d %s %s %f %d %d", &anlage.inventarnr, anlage.anlagenbez, anlage.standort, &anlage.basiswert, &anlage.nutzdauer, &anlage.anschjahr) != eof) { if(index > 0) { size++; realloc(anlage_arr, size * sizeof(anlage)); } anlage_arr[index] = anlage; index++; } return size; }
i know have initialize new pointer anlage
type , check if it's null
after call realloc
, since function crashes program, i've skipped in case.
in addition many fine points made in comments above, need aware realloc
returns pointer memory block has allocated which may not in same location pointer passed. in other words, after calling realloc
original memory pointed pointer (in case, anlage_arr
) may have been released, , pointer returned realloc
must used access re-allocated memory.
i suggest might want rewrite function follows:
size_t verarbeite_anlagendatei(anlage **p_anlage_arr) { file *fp; anlage anlage; fp = fopen("anlagen.dat", "r"); if(fp == null) { printf("anlagedatei existiert nicht. bitte mit menuepunkt (0) weiter machen.\n"); return 0; } int index = 0; size_t size = 1; while(fscanf(fp, "%d %s %s %f %d %d", &anlage.inventarnr, anlage.anlagenbez, anlage.standort, &anlage.basiswert, &anlage.nutzdauer, &anlage.anschjahr) != eof) { if(index > 0) { size++; *p_anlage_arr = realloc(*p_anlage_arr, size * sizeof(anlage)); } (*p_anlage_arr)[index] = anlage; index++; } return size; }
a call function like
anlage *anlage_arr; size_t sz; anlage_arr = malloc(sizeof(anlage)); sz = verarbeite_anlagendatei(&anlage_arr);
best of luck.
Comments
Post a Comment