【发布时间】:2016-03-31 16:42:21
【问题描述】:
这里有一些嵌套结构:
struct bat
{
int match,run,fifty,best;
double average,strike_rate;
};
struct ball
{
char *best;
int match,wicket,fiveW;
double economy,average;
};
struct Player
{
char *name;
char *country;
char *role;
struct bat *batting;
struct ball *bowling;
};
struct Team
{
char *name;
char *owner;
char *rank;
char *worth;
char *match;
char *won;
char *lost;
struct Player *plist;
} *team;
下面我使用*team指针动态分配了7个struct Team类型的数组,每个指针包含16个使用*plist的struct Player类型数组。 struct Player 也有两个嵌套结构。
int i,j;
team=(struct Team *) calloc(7,sizeof(struct Team));
for(i=0; i<7; i++)
{
(team+i)->name=( char*) malloc(1*100);
(team+i)->owner=( char*) malloc(1*100);
(team+i)->rank=( char*) malloc(1*100);
(team+i)->worth=( char*) malloc(1*100);
(team+i)->match=( char*) malloc(1*100);
(team+i)->won=( char*) malloc(1*100);
(team+i)->lost=( char*) malloc(1*100);
(team+i)->plist=(struct Player *) calloc(16,sizeof(struct Player));
for(j=0; j<16; j++)
{
(((team+i)->plist)+j)->name=( char*) malloc(1*100);
(((team+i)->plist)+j)->country=( char*) malloc(1*100);
(((team+i)->plist)+j)->role=( char*) malloc(1*100);
(((team+i)->plist)+j)->batting=(struct bat *) malloc(sizeof(struct bat));
(((team+i)->plist)+j)->bowling=(struct ball *) malloc(sizeof(struct ball));
((((team+i)->plist)+j)->bowling)->best=(char*) malloc(1*100);
}
}
现在我已经为所有这些赋值并完成了一些任务。现在是释放所有dynamically allocated arrays 的时候了。释放上面分配的所有内容的正确方法是什么?
我尝试像下面这样释放,但程序获取 run-time error 并崩溃:
for(i=0; i<7; i++)
{
free((team+i)->name);
free((team+i)->owner);
free((team+i)->rank);
free((team+i)->worth);
free((team+i)->match);
free((team+i)->won);
free((team+i)->lost);
for(j=0; j<16; j++)
{
free((((team+i)->plist)+j)->name);
free((((team+i)->plist)+j)->country);
free((((team+i)->plist)+j)->role);
free((((team+i)->plist)+j)->batting);
free(((((team+i)->plist)+j)->bowling)->best);
free((((team+i)->plist)+j)->bowling);
}
free(((team+i)->plist));
}
free(team);
如何正确释放所有dynamically allocated memory?
【问题讨论】:
-
释放你
malloc()ated的每个指针,按照分配的相反顺序。 -
OT:不要投射
malloc,而sizeof(char)始终是1 -
是的,只是颠倒阅读,(并考虑转向 C++)。
-
考虑到大多数内部成员
malloc是固定长度硬编码到源代码中的,我很难理解您为什么还要费心去做任何,而是首先拥有像char name[100]这样的大小成员。动态分配:仅仅因为你可以并不意味着你应该。 -
另外,那些括号很难看。
(team+q)->plist)+b)->bowling)->best应该写成team[q].plist[b].bowling->best。
标签: c pointers struct dynamic-allocation