Here are some nested structures:
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;
Below I dynamically allocated an array of 7 struct Team
type using *team
pointer each of which contains 16 struct Player
type array using *plist
. struct Player
has also two nested structures.
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);
}
}
Now I have assigned values to all of these and done some tasks. It's time to free all those dynamically allocated arrays
. What is the correct way to free everything allocated above?
I tried to free like below but the program fetches run-time error
and crashes:
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);
How to free all those dynamically allocated memory
correctly?