【发布时间】:2019-10-28 16:46:25
【问题描述】:
我有一个名为addMod 的函数,调用该函数时,会将一个节点添加到Module 结构LinkedLists 数组的某个索引,该数组称为modules,包含在System 结构中。 Module 结构有一个字符串字段、两个 int 字段和一个指向下一个 Module 的指针,前三个字段根据 addMod 中提供的参数进行初始化。 addMod大致是这样的:
int addMod(System *system, const char *text, int num1, int num2, int index) {
Module *temp = malloc(sizeof(Module));
Module *current;
temp->next = NULL;
if ([any of the constructors are invalid]) return 0;
temp->text = malloc(strlen(text)+1);
strcpy(temp->text, text);
temp->num1 = num1; temp->num2 = num2;
if (!system->modules[index]) {
system->modules[index] = temp; //If there are no modules in the LinkedList at the given index, makes the head = temp.
}
else {
if (system->compare(temp, system->modules[index]) <= 0) { //compare is a func pointer field of system that compares two Modules to see in what order they should be. Here, we check if temp should become the head of modules[index].
temp->next = system->modules[index]; //Assigns the current head as the module following temp.
system->modules[index] = temp; //Makes temp the current head.
}
else {
current = system->modules[index];
while (current->next && system->compare(temp, current->next) > 0) { //While current isn't the last node in the LinkedList and temp comes after the node after current
current = current->next;
}
temp->next = current->next; //Adds temp in between current and current->next.
current->next = temp;
}
}
return 1;
}
以上所有操作都按预期工作,除了打印system 的内容时,控制台指示存在内存泄漏,我假设是因为根据 valgrind 告诉我的信息,我未能正确释放temp。我的问题是不知道在哪里释放它——似乎我把它放在任何地方都会在打印内容后导致段错误。根据我的理解,我必须确保没有其他变量取决于temp 所持有的值,但考虑到我的 if 语句的每个可能结尾都导致分配@,我似乎无法找到一种方法来做到这一点987654333@ 到modules 内的一个节点。将free(temp) 放在逻辑和return 1 之间也会产生段错误,我假设是因为我经常在连续多次调用addMod 时再次malloc temp。
总而言之,要向可能填充或不填充的 LinkedList 添加一个新节点,其中这个新节点可以插入到 LinkedList 中的任意位置,我必须将内存分配给一个临时节点,以便我以后可以插入。成功插入节点后,在哪里释放分配的内存?
【问题讨论】:
-
添加到链表时,没有“临时”节点。只有“添加”节点,而这正是您在这里所拥有的。每当需要清理和/或以其他方式管理对象时,您都应该释放“系统”(无论是什么)实例中的 所有 节点。也就是说,如果你真的感兴趣的话,这可以在大约 1/5 的代码中完成,并且仅供参考,
if ([any of the constructors are invalid]) return 0;应该在 beforemalloc之前完成。如果这样做了它所声称的(仅返回 0),那肯定是一个泄漏。 -
可以有根据程序逻辑删除系统模块的功能,可以释放模块。仅仅免费是不够的,但 Modules->text 也必须被释放。如果免费导致段错误,则可能 temp 正在实际代码中重新分配垃圾或未分配地址,可以在实际代码中或使用 gdb 进行跟踪。
-
@WhozCraig 您的第一句话实际上非常有帮助。我想我认为 temp 是在我将它的“副本”放入链表之后需要摆脱的东西,我现在看到的并不是它的工作原理。我重写了一个单独的函数,该函数应该清除所有内容以遍历每个链表的每个成员并释放节点本身后面的文本字段,并且我已经修复了内存泄漏。感谢您的帮助。
-
@user11500789 你是不是有点好奇如何让插入功能更简单更?
-
@WhozCraig 是的,请
标签: c struct linked-list malloc free