[英]structs free up memory function - c
I have a program i made and its running perfectly!我有一个我制作的程序并且它运行完美! the only problem is the free pointers function this is a link for the full code https://codeshare.io/aVE3n3
唯一的问题是自由指针 function 这是完整代码https://codeshare.io/aVE3n3的链接
The problem is that i success to free the player name pointer, but after the program doesn't let me free the player's pointer.问题是我成功释放了播放器名称指针,但是在程序不让我释放播放器指针之后。 I'd love to get some help, thanks.
我很想得到一些帮助,谢谢。
void freeTeam(team* t,int size)
{
int temp;
for (int j = 0; j < size; j++)
{
temp = t[j].current_players;
for (int i = 0; i < temp; i++)
{
free(t->players[i].name);
}
free(t->players);
for (int i = 0; i < temp; i++)
{
free(t[i].team_name);
}
free(t[j]);
}
}
The first wrong part is第一个错误的部分是
t->players = (player**)calloc(t->max_players, sizeof(player*));
in initTeam()
.在
initTeam()
中。
t->players
has type player*
and its element type is player
. t->players
的类型为player*
,其元素类型为player
。 In typical environment, player
(one pointer and other elements) consume more memory than player*
(one pointer), so you won't allocate enough memory here.在典型环境中,
player
(一个指针和其他元素)比player*
(一个指针)消耗更多的 memory,因此您不会在此处分配足够的 memory。
It should be它应该是
t->players = calloc(t->max_players, sizeof(player));
or或者
t->players = calloc(t->max_players, sizeof(*t->players));
(note: c - Do I cast the result of malloc? - Stack Overflow ) (注意: c - 我要转换 malloc 的结果吗? - 堆栈内存溢出
The second wrong part is the freeTeam
function.第二个错误的部分是
freeTeam
function。
free(t->players[i].name);
may cause double (or more) free because only t[0]
is dealt with.t[0]
。free(t[i].team_name);
may cause double (or more) free and/or out-of-bounds read because the usage of loop is wrong.free(t[j]);
is invalid because structure is not a pointer. It should be它应该是
void freeTeam(team* t,int size)
{
int temp;
for (int j = 0; j < size; j++)
{
temp = t[j].current_players;
for (int i = 0; i < temp; i++)
{
free(t[j].players[i].name);
}
free(t[j].players);
free(t[j].team_name);
}
}
after that, t
should be freed after freeTeam(t,size);
之后,应该在
freeTeam(t,size);
t
释放 t; in main()
.在
main()
中。
Additionaly, you should use standard int main(void)
in hosted environment instead of void main()
, which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.另外,您应该在托管环境中使用标准
int main(void)
而不是void main()
,这在 C89 中是非法的,并且在 C99 或更高版本中是实现定义的,除非您有特殊原因使用非标准签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.