我正在使用在线教程来学习 C,这样我就可以学习 obj-C 以获得潜在的工作 ( http://www.learn-c.org/en/Linked_lists )
我正在上一个类,您必须按值从链接列表中删除第一个节点,我似乎成功地做到了这一点。然后我将其删除具有该值的所有节点,这似乎也有效。
typedef struct node {
int val;
struct node * next;
int large[2500];
} node_t;
int remove_by_value(node_t ** head, int val) {
if (*head == NULL){
return -1;
}
node_t *current = *head;
node_t *previous = NULL;
do{
if(current->val == val){
node_t *toDelete = current;
if(previous != NULL){ //not 1st on the list
previous->next = current->next;
current = previous ->next;
}
else{ //node to remove is 1st on the list
*head = (*head)->next; //
current = *head; //current = the new head
}
free(toDelete);
}
else{
previous = current;
current = current->next;
}
}while(current != NULL);
return -1;
}
int main(){
node_t *test_list = malloc(sizeof(node_t));
node_t *current = test_list;
current->val = 37;
for(int i=1; i < 300000; i++){
current->next= malloc(sizeof(node_t));
current = current->next;
current->val = rand()%3;
}
print_list(test_list);
remove_by_value(&test_list, 2);
print_list(test_list);
}
//更新: 似乎正在进行一些释放,但我不了解内存使用情况。
sizeof(node_t) ~ 10kB 300,000 node_t = 3 GB//我希望程序此时使用 3GB
但是,在程序中创建 300,000 个 node_t 之后,内存使用量(在 Xcode 的分析器中)仅显示 1.16GB(这是一些优化吗,应该是 3GB?)我调用按值删除(列表仅包含值)从 0 到 3)
{before list created} // mem usage 288KB
{link list created} // mem usage 1.16GB
remove_by_value(&test_list, 2); // mem usage 1.39GB
remove_by_value(&test_list, 3); // "" 1.17GB
remove_by_value(&test_list, 1); // "" 759MB (seems correct)
remove_by_value(&test_list, 0); // "" 20MB (why this big still?)
我重新运行了程序,并将node_t更改为每 block 100KB,这意味着列表应该是30GB。内存激增至 2GB 以上,但缓慢下降至 500MB 左右。有谁知道这是为什么吗?
最佳答案
在某些外部应用程序中观察“内存使用情况”并不能提供您正在寻找的数字。您实际看到的是您的程序从操作系统请求的内存量。操作系统不知道您的程序实际上如何使用该内存。
在您的情况下,C 运行时库正在使用内存本身并跟踪自己释放和分配的内容。它不需要通知操作系统该位已分配,该位之前已分配但现在已释放,该位之前已请求但尚未使用。
您将看到的效果是,当您的程序运行时,从操作系统的角度请求的内存量可能不会减少。这个是正常的。
关于c - 学习C - 为什么这个方法不释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856000/