I have a struct like so,
typedef struct Player {
char *name;
char *heroID;
char *heroName;
int slotNo;
} Player;
I then define it as a statically allocated array
Player players[10];
My program may have to exit when I haven’t completely allocated all the char* fields of each Player struct in players and I have decided that I will free any allocated memory before exiting even though modern OS’s don’t require you to because it is good programming practice to do so.
However, I can’t just loop through players and free(player[i].name) etc because it could be uninitialized.
Is the only way of getting around this problem, manually initializing each char pointer to NULL after I define the array and then when freeing memory, check to see if the pointer is NULL or not to decide whether I should free it?
If so, what is the best way of initializing, for loop and manual assignment or defining values when i declare the players array through the use of braces. Or is there another way?
It’s definitely not the only way, but it’s the most common and standard way to do so. In fact, most programmers will always initialize pointers to zero to prevent seg faults.
The best way to initialize is to just create a
forloop ormemseteverything to zero (or usecalloc, which is the easiest).