私はこれについて何時間も頭を悩ませてきました。これは、テキスト ファイルから構造体にデータを読み取ります (各行には 4 つの文字列があり、各行は新しい学生を表します)。realloc でセグ フォールトが発生しています (終わり近く)。ポインターが malloc/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;
}
このセグフォルトの原因は何ですか?
前もって感謝します、
ガス