我有一个这样的结构,
typedef struct Player {
char *name;
char *heroID;
char *heroName;
int slotNo;
} Player;
然后我将它定义为一个静态分配的数组
Player players[10];
当我还没有完全分配 players
中每个 Player
结构的所有 char*
字段时,我的程序可能不得不退出,并且我我决定在退出前释放所有分配的内存,即使现代操作系统不需要您这样做,因为这样做是很好的编程习惯。
但是,我不能只循环遍历 players
和 free(player[i].name)
等,因为它可能未初始化。
解决这个问题的唯一方法是在定义数组后手动将每个 char 指针初始化为 NULL,然后在释放内存时检查指针是否为 NULL 以决定是否释放它?
如果是这样,当我通过使用大括号声明播放器数组时,初始化、for 循环和手动赋值或定义值的最佳方法是什么。还是有别的办法?
最佳答案
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?
这绝对不是唯一的方法,但它是最常见和最标准的方法。事实上,大多数程序员总是将指针初始化为零以防止段错误。
最好的初始化方法是只创建一个for
循环或memset
一切都归零(或使用calloc
,这是最简单的).
关于c - 释放可能未初始化的结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8999994/