【发布时间】:2017-04-21 16:44:22
【问题描述】:
所以我对如何进行正确的内存管理有一些疑问。
基本上我的问题是,例如,当我使用此代码时会发生什么(如下所示)。是否需要释放它以防止内存泄漏?
void traverseLeftRight(struct node *head){
current = head;
if(current == NULL){
printf("There are no nodes within the list\n");
}
while(1){
if(current != NULL){
printf("left to right output: %d\n", current -> value);
current = current -> next;
}else{
break;
}
}
}
此外,如果我在列表的中断部分执行此操作,那么 free(current) 和 current = NULL 是否会中断该列表。另外,这样的事情会破坏指向变量而不影响它对应的节点吗?
void traverseLeftRight(struct node *head){
current = head;
if(current == NULL){
printf("There are no nodes within the list\n");
}
while(1){
if(current != NULL){
printf("left to right output: %d\n", current -> value);
current = current -> next;
}else{
free(current);
current = NULL;
break;
}
}
}
【问题讨论】:
-
每个分配都应该与一个空闲空间配对,在不再需要分配的空间后执行。仅仅访问分配的内存不会产生任何额外的义务。
-
至于您提议的代码变体,这绝对没有意义。仅当
current已计算为NULL时,才输入else块。释放它或将其冗余设置为NULL没有用。 -
好的,谢谢,当我使用类似 current 的东西时,我最初想到的是我需要释放我用于它的值。感谢您澄清这一点。
-
所以为了清楚起见,我只会在我当前从我正在使用的列表中删除一个节点时释放,因为这是需要分配或在程序结束时?那么除非由 c 库函数(一般而言)指定,否则没有其他地方?
-
是的,当您从列表中删除一个动态分配的节点时,自然会释放它的内存,并且在任何情况下都不能在它保持 in 时释放它的内存i> 列表。细节需要参考具体代码。
标签: c pointers memory-management