为什么不malloc的"使用了"在我的电脑上的内存? [英] Why is malloc not "using up" the memory on my computer?

查看:75
本文介绍了为什么不malloc的"使用了"在我的电脑上的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个程序,分配256 MB的内存,而用户presses ENTER后,释放内存并终止。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释主要(无效){
    字符* P,S [2];    P =的malloc(256 * 1024 * 1024);
    如果(P == NULL)
        出口(1);    的printf(分配);
    与fgets(S,2,标准输入);
    自由(对);
    返回0;
}

我跑这个节目多次,后台运行他们每个人,直到不再有可分配足够的内存。然而,这永远不会发生。我跑了Linux的命令,甚至运行此程序多次后,可用内存不降了近多达256 MB。

然而,在另一方面,如果我用释放calloc 而不是的malloc 再有一个巨大的差别:

P =释放calloc(256 * 1024 * 1024,1);

现在,如果我运行程序和背景,然后重复,我每次运行它​​的时候,空闲内存下降256 MB。为什么是这样?为什么的malloc 不会导致可用内存来改变,但释放calloc 呢?


解决方案

的malloc()做的的使用内存。它分配它。

在您分配内存,通过分配一些数据使用。

 为size_t大小= 256 * 1024 * 1024;
P =的malloc(大小);
如果(P!= NULL){
  memset的(P,123,大小);
}

一些平台实现的malloc()是这样的方式的存储器的物理地消耗,不会发生,直到字节(或者更可能的基团或页内的字节字节)进行访问。

释放calloc()可能会或可能不会真正的使用的内存无论是。系统可以的地图的大量内存到同一个物理清零的内存,至少要等到数据变得有趣。看到
为什么的malloc + memset的比释放calloc?

So I have this program that allocates 256 MB of memory, and after the user presses ENTER it frees the memory and terminates.

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

int main(void) {
    char *p, s[2];

    p = malloc(256 * 1024 * 1024);
    if ( p == NULL) 
        exit(1);

    printf("Allocated"); 
    fgets(s, 2, stdin);
    free(p);
    return 0;
}

I ran this program multiple times and backgrounded each of them until there is no longer enough memory that can be allocated. However, that never happens. I ran a linux top command and even after running this program many times, the free memory never goes down by nearly as much as 256 MB.

However, on the other hand, if I use calloc instead of malloc then there is a HUGE difference:

p = calloc(256 * 1024 * 1024, 1);

Now if I run the program and background it, and repeat, every time I run it, the free memory goes down by 256 MB. Why is this? Why does malloc not cause the available free memory to change, but calloc does?

解决方案

malloc() does not use memory. It allocates it.

After you allocate the memory, use it by assigning some data.

size_t Size = 256 * 1024 * 1024;
p = malloc(Size);
if (p != NULL) {
  memset(p, 123, Size);
}

Some platforms implement malloc() is such a way that the physically consumption of memory does not occur until that byte (or more likely a byte within a group or "page" of bytes) is accessed.

calloc() may or may not truly use the memory either. A system could map lots of memory to the same physical zeroed memory, at least until the data gets interesting. See Why malloc+memset is slower than calloc?

这篇关于为什么不malloc的&QUOT;使用了&QUOT;在我的电脑上的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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