【发布时间】:2011-07-13 14:01:47
【问题描述】:
我已经为此挠头好几个小时了。这会将文本文件中的数据读取到结构中(每行有四个字符串,每行代表一个新学生)。我在 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;
}
是什么导致了这个段错误?
提前致谢,
格斯
【问题讨论】:
-
尽管不是段错误的根本原因,但当 realloc 无法分配更多内存时,您使用 realloc 的方式可能会导致内存泄漏,因为它会返回 NULL 并且您会丢失指向前一个缓冲区的指针