c - 不能只释放一个动态分配的元素
问题描述
所以基本上我有一个功能,它是一个大学结构并用学生填充它。这一切都有效!当大学返回主大学时,所有值都存储在主大学内。
然后,当我尝试释放它(主要)时,它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);
解决方案
这条线
tempUni.students = (Stud*)malloc(sizeof(temp));
只为一个指针分配内存。代码不容易理解,但也许应该是
tempUni.students = malloc(i * sizeof(Stud));
推荐阅读
- selenium - 有什么方法可以轻松地将 ChromeDriver 添加到程序中
- firebase - 为什么我的 Firebase 动态链接会变成分支动态链接?
- typescript - Firebase 函数在尝试部署时导致错误
- linux - $${!} 在 bash 中是什么意思?
- unity3d - 使用 Sprite Shape Controller 编辑创建一个圆
- laravel - 在 Laravel Nova 中上传多张图片
- javascript - Javascript If 语句 HTML
- javascript - 如何获取并等待 5 秒并获取页面的源代码
- javascript - innerhtml 不适用于长字符串 html
- linux - 需要想办法解决Linux udhcpc上的这个字符串变量