学习C - 为什么这种方法不能释放内存?

时间:2014-07-20 23:48:21

标签: c linked-list malloc free

我正在使用在线教程学习C,这样我就可以学习obj-C的潜在工作(http://www.learn-c.org/en/Linked_lists

我正在上课,您必须按值从链接列表中删除FIRST节点,我似乎成功地这样做了。然后我在它删除具有该值的所有节点的位置,这似乎也有效。

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&#39;分析器内)只显示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更改为100KB,这意味着列表应为30GB。内存峰值超过2GB,但慢慢下降到大约500MB。有谁知道这是为什么?

1 个答案:

答案 0 :(得分:3)

观看&#34;内存使用情况&#34;在某些外部应用程序中没有提供您正在寻找的数字。您实际看到的是程序从操作系统请求的内存量。操作系统不知道您的程序实际上如何使用该内存。

在您的情况下,C运行时库正在使用内存本身并跟踪已释放和分配的内容。它不需要通知操作系统该位已被分配,并且该位在之前被分配但现在已被释放,并且之前已请求该位但尚未使用。

您将看到的效果是,当您的程序运行时,从操作系统的角度请求的内存量可能不会下降。这个是正常的。