gpt4 book ai didi

c - 无法释放我所有的内存

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:45 25 4
gpt4 key购买 nike

我是 C 的新手,很难完全理解指针
当前手头的任务是从结构命令中清除每个数组(结构显示在底部)。
希望有人能识别出一些可怕的错误,比如多次释放某些东西。我知道我的代码可能看起来很糟糕,但感谢您花时间查看它。
我目前尝试清除所有内容:

void clear_commands(Commands *commands) {
Command *compile, *test, *temp;
if (commands != NULL) {
compile = commands->compile;
while (compile != NULL) {
temp = compile;
compile = compile->next;
free(temp);
}

test = commands->test;
while (test != NULL) {
temp = test;
test = test->next;
free(temp);
}

free(commands);
commands = NULL;
}
}

这些是类型定义:

typedef struct Command{
char *command;
struct Command *next;
} Command;

typedef struct {
Command *test;
Command *compile;
} Commands;

添加:read_commands

Commands read_commands(const char *compile_cmds, const char *test_cmds) {
FILE *f;
Commands *commands = malloc(sizeof(Commands));
Command *compile, *test;
char temp[257];

if (compile_cmds == NULL || test_cmds == NULL)
exit(0);

compile = malloc(sizeof(Command));
test = malloc(sizeof(Command));
commands->compile = compile;
commands->test = test;

f = fopen(compile_cmds,"r");
if (f != NULL)
while(!feof(f)) {
if(fgets(temp, 257, f) != NULL) {
compile = malloc(sizeof(Command));
compile->command = malloc(strlen(temp) + 1);
strcpy(compile->command, temp);
compile->next = malloc(sizeof(Command));
compile = compile->next;
}
}
fclose(f);
...
return *commands;
}

最佳答案

Commands read_commands(const char *compile_cmds, const char *test_cmds) {
FILE *f;
Commands *commands = malloc(sizeof(Commands));
Command *compile, *test;
char temp[257];

if (compile_cmds == NULL || test_cmds == NULL)
exit(0);

compile = malloc(sizeof(Command));
test = malloc(sizeof(Command));
commands->compile = compile;
commands->test = test;

f = fopen(compile_cmds,"r");
if (f != NULL)
while(!feof(f)) {
if(fgets(temp, 257, f) != NULL) {
compile->command = malloc(strlen(temp) + 1);
strcpy(compile->command, temp);
compile->next = malloc(sizeof(Command));
compile = compile->next;
}
}
fclose(f);
...
return *commands;
}

关于c - 无法释放我所有的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34098547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com