为什么free()不能真正释放内存? [英] Why free() doesn't really frees memory?

查看:572
本文介绍了为什么free()不能真正释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些分配和释放内存的测试.这是我正在使用的代码:

i'm doing some tests allocating and deallocating memory. This is the code i'm using:

#include <stdlib.h>
#include <stdio.h>

#define WAVE_SIZE 100000000

int main(int argc,char* argv[]){

    int i;
    int **p;

    printf("%d allocs...\n",WAVE_SIZE);

    // Malloc
    printf("Allocating memory...\n");
    p = (int**)malloc(WAVE_SIZE*sizeof(int*));
    for(i = 0;i < WAVE_SIZE;i++)
            p[i] = (int*)malloc(sizeof(int));

    // Break
    printf("Press a key to continue...\n");
    scanf("%*s");

    // Dealloc
    printf("Deallocating memory...\n");
    for(i = 0;i < WAVE_SIZE;i++)
            free(p[i]);             
    free(p);

    // Break
    printf("Press a key to continue...\n");
    scanf("%*s");

    return 0;
}

在休息期间,我检查该进程使用的总内存,但看不到我期望的值.

During breaks i check the total memory used by the process and i don't see what i expect.

在第一次暂停之前,我看到内存消耗增加.但是,在第二次暂停时,我看不到它被释放.

Until the first pause i see memory consumption increasing. However, at second pause I do not see it being released.

这是OS的东西吗?如果我的计算机负载很高,我没有可用的内存并且另一个进程尝试分配,会发生什么情况?

Is this a OS thing? What happens if my machine's load is high, i don't have free memory and another process try to alloc?

推荐答案

free不一定会将内存释放回操作系统.大多数情况下,它只是将该内存区域放回空闲块列表中.这些空闲的块可重新用于下一次malloc的调用.

free does not necessarily release the memory back to the operating system. Most often it just puts back that memory area in a list of free blocks. These free blocks could be reused for the next calls to malloc.

这篇关于为什么free()不能真正释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆