Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

【编程小白】用C语言测试电脑可分配的最大内存

代码如下

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

int main(void) {

    void * p;
    int sum = 0;
    while (p = malloc(1024*1024*1024)) {
        sum++;
    }
    printf("可以分配的最大内存为%dGB
",sum);
    free(p);
    return 0;
}

每次分配1个GB,sum的数字就加1
按理说这个代码也没问题啊,但是我计算出来的结果是这样的。

Test(3433,0x1000dedc0) malloc: can't allocate region
:*** mach_vm_map(size=1073741824, flags: 40000100) failed (error code=3)
Test(3433,0x1000dedc0) malloc: *** set a breakpoint in malloc_error_break to debug
可以分配的最大内存为131063GB
Program ended with exit code: 0

本人用的是MacBook Pro
image.png

电脑内存是8GB
为什么算出来可以分配有131063GB啊,这个我有点不理解,是我代码写错了么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以看看这里有相关讨论,https://stackoverflow.com/que...

简单来说os分配给你的虚拟内存而不是真实内存,同时os采用延迟初始化策略,分配给你的虚拟内存是要到用的那一刻才占用真实内存。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...