私は数時間頭を掻き回してきました。これは、テキストファイルから構造体にデータを読み込みます(各行には4つの文字列があり、各行は新しい生徒を表します)。私はrealloc(最後の近く)にsegフォルトを得ています。私はポインタがmalloc/reallocとどのようにやり取りしているのか理解していないとの疑いがあります。構造体の配列にreallocを使用する
struct student* createInitialStudentArray(FILE *fp) {
char buf[20+1] = {0};
int word = 1, studcount = 1;
struct student* studentArray = malloc(sizeof(struct student));
assert(studentArray != NULL);
while (fscanf(fp, " %20s", buf) != EOF) {
if (word % 4 == 1) {
sscanf(buf, "%4d", &studentArray[studcount].studentID);
word++;
}
else if (word % 4 == 2) {
strcpy(studentArray[studcount].lastName, buf);
word++;
}
else if (word % 4 == 3) {
strcpy(studentArray[studcount].firstName, buf);
word++;
}
else if (word % 4 == 0) {
sscanf(buf, "%10lld", &studentArray[studcount].phoneNumber);
word = 1;
studcount++;
studentArray = realloc(studentArray, studcount * sizeof(struct student));
assert(studentArray != NULL);
}
}
return studentArray;
}
このセグフォルトの原因は何ですか?あなたの配列がstudcount
の要素を持っている場合は、事前に
おかげで、
のGus
であなたの内側のループを書き換えたい
のreallocは、より多くのメモリを割り当てることができないとき、あなたはreallocのを使用している方法は、メモリリークにつながる可能性なぜなら、NULLを返して、前のバッファへのポインタを失うからです。 – Vitor