因此,基本上我有一个功能可以使大学结构填充,并将其与学生一起填充。一切都起作用!当大学返回MAIN时,所有的价值都存储在主要大学中。
然后,当我尝试释放它时(主要(由于某种原因,它在braude.students[2].name
上漏洞。
例外是:ctrlsvalidheappointer(block(。
为什么它可以释放所有其他动态分配的名称,但不能释放这个名称?
university getStudentInfo(FILE * file) // Definition of the getStudentInfo function
{ // This function reads student information from a file
// and updates a university with this information using a pointer
int i = 1, j;
char name[99]; // A temporary name to hold the student's name.
university tempUni; // A temporary university to hold values
Stud * temp = (Stud*)malloc(sizeof(Stud)); // Allocating memory
// for an array of students
if (temp == NULL) // In case there wasn't enough space
Error_Msg("Couldn't allocate enough memory.");
while (getInfo(file, name, &temp[i - 1]) == 8)
// Using getInfo==8, because in each row, there are 8 variables to scan
{
temp[i - 1].name = (char*)malloc(sizeof(char)*strlen(name) + 1);
// Allocating memory for the current element's name.
if (temp[i - 1].name == NULL) // In case there wasn't enough space, terminate
Error_Msg("Couldn't allocate enough memory.");
strcpy(temp[i - 1].name, name);
// If there was, copy the name from "name" to the current student's name.
i++; // Increase i by one to have space in memory for one more student
temp = (Stud*)realloc(temp, i * sizeof(Stud));
// Realloc temp, to make more space for one more student.
if (temp == NULL) // In case there wasn't enough space, terminate.
Error_Msg("Couldn't allocate enough memory.");
}
tempUni.students = (Stud*)malloc(sizeof(temp));
// Allocating memory for students of the university, with the size of temp
if (tempUni.students == NULL)
// In case there wasn't enough space, terminate.
Error_Msg("Couldn't allocate enough memory.");
tempUni.students->marks[5] = ' '; // Making the last mark in the string
tempUni.students = temp; // Let the temporary university array of students be temp
tempUni.studentCount = i - 1; // How many students
return tempUni; // Update the pointed university to have the same values as tempUni
}
但是,当我在主机中释放动态分配的内存时,如那样:
free(braude.students[0].name);
free(braude.students[1].name);
free(braude.students[2].name); // Crashes here???
free(braude.students[3].name);
free(braude.students);
此行
tempUni.students = (Stud*)malloc(sizeof(temp));
仅为一个指针分配内存。该代码不容易遵循,但也许应该是
tempUni.students = malloc(i * sizeof(Stud));