为什么 malloc 没有“用完"?我电脑上的内存? [英] Why is malloc not "using up" the memory on my computer?

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

问题描述

所以我有一个分配 256 MB 内存的程序,在用户按下 ENTER 后它释放内存并终止.

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;
}

我多次运行这个程序并对每个程序进行后台处理,直到没有足够的内存可以分配.然而,这永远不会发生.我运行了一个 linux top 命令,即使在多次运行该程序之后,可用内存也从未减少近 256 MB.

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.

然而,另一方面,如果我使用 calloc 而不是 malloc 那么就会有很大的不同:

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

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

现在,如果我运行该程序并将其后台运行,然后重复,每次运行它时,空闲内存都会减少 256 MB.为什么是这样?为什么 malloc 不会导致可用空闲内存发生变化,但 calloc 会发生变化?

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()使用内存.它分配它.

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);
}

某些平台实现 malloc() 是这样一种方式,在访问该字节(或更可能是一组或页面"字节中的一个字节)之前,不会发生内存的物理消耗.

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

calloc() 可能也可能不会真正使用内存.系统可以映射大量内存到相同的物理归零内存,至少在数据变得有趣之前是这样.看为什么 malloc+memset 比 calloc 慢?

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 没有“用完"?我电脑上的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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