本文介绍了如何正确安全地释放()使用C中嵌套结构的所有内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我嵌套了四个不同的结构层。代码如下:

  typedef struct System system; 
typedef struct College大学;
typedef struct学生学生;
typedef struct Family家庭;

#define MAX_COLLEGES 10
#define MAX_NAME_LEN 32
#define MAX_STUDENTS 10

结构系统{
college * Colleges [MAX_COLLEGES];
};

struct College {
char name [MAX_NAME_LEN];
学生*学生[MAX_STUDENTS];
};

结构学生{
字符名称[MAX_NAME_LEN];
int id;
家庭*家族; //是错别字
};

struct Family {
char parentName [MAX_NAME_LEN];
char motherName [MAX_NAME_LEN];
};

然后我为所有这些人分配了内存(不确定是否正确分配了所有人),如下所示:

  system * collegeSys = malloc(sizeof(system)); 
大学*学院= malloc(sizeof(college));
学生*学生= malloc(sizeof(学生));
family * fam = malloc(sizeof(family));

//然后是初始化
...
...
...

现在,我需要删除 collegeSys 结构以及与其关联的所有内容。因此,我不知道是否可以仅释放第一个 collegeSys 结构而不释放任何其他结构,例如:

 免费(collegeSys); 

或者为了删除与之相关的任何内容,我必须自下而上释放所有内容,像这样:

 免费(家庭); 
免费(学生);
免费(大学);
free(collegeSys);

或者为此,我什至必须释放每个结构体中包含的所有内容并自底向上释放它们,就像这样:

 免费(fam-> FatherName); 
免费(fam-> motherName);
免费(fam);
免费(学生->名称);
免费(学生-> id);
免费(学生-> fam);
免费(学生)

。直到

免费(collegeSys->大学);
免费(collegeSys);

哪个是释放内存的正确和安全的方法?还是它们都不是?

解决方案

我不太了解具有指针数组的意义,可以用指针来完成。



定义:

  struct系统{
大学*学院;
};

struct College {
char name [MAX_NAME_LEN];
学生*学生;
};

结构学生{
字符名称[MAX_NAME_LEN];
int id;
家族*家族;
};

struct Family {
char parentName [MAX_NAME_LEN];
char motherName [MAX_NAME_LEN];
};

分配和初始化:

  system * collegeSys = malloc(sizeof(* collegeSys)); 
collegeSys-> colleges = malloc(MAX_COLLEGES * sizeof(*(collegeSys-> colleges))));
collegeSys-> colleges->学生= malloc(MAX_STUDENTS * sizeof(*(collegeSys-> colleges->学生))));
collegeSys-> colleges-> students-> fam = malloc(sizeof(*(collegeSys-> colleges-> students-> fam)));

释放:

 免费(collegeSys-> colleges->学生-> fam); 
免费(collegeSys-> colleges->学生);
free(collegeSys-> colleges);
free(collegeSys);






更新:

 collegeSys->colleges->students[0] = A;
 collegeSys->colleges->students[1] = B;
 collegeSys->colleges->students[2] = C;
 collegeSys->colleges->students[3] = D;

Should do it.

If yo have array of students you can use memcpy or copy in loop.

struct student stud[MAX_STUDENTS] = {...};

memcpy(collegeSys->colleges->students[2], stud, MAX_STUDENTS);

or

for (int i = 0; i< MAX_STUDENTS; i++)
     collegeSys->colleges->students[i] = stud[i];


Note:

You can assign the array to collegeSys->colleges->students in that case you don't need dynamic memory allocation or freeing.

 // collegeSys->colleges->students = malloc(MAX_STUDENTS * sizeof(*(collegeSys->colleges->students)));  //Leaks memory

 collegeSys->colleges->students = stud;

//free(collegeSys->colleges->students); //wrong

这篇关于如何正确安全地释放()使用C中嵌套结构的所有内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:38
查看更多