因此,基本上,我有一个函数,它具有大学结构并将其填充为学生。一切正常!大学返回主大学后,所有值都存储在主大学内。
然后,当我尝试释放它时(主要),
它由于某种原因而在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] = '\0'; // Making the last mark in the string \0
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
}
但是当我释放main中动态分配的内存时,像这样:
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);
答案 0 :(得分:0)
此行
tempUni.students = (Stud*)malloc(sizeof(temp));
仅为一个指针分配内存。该代码不容易理解,但也许应该
tempUni.students = malloc(i * sizeof(Stud));