当前位置:网站首页>问题来了:4GB物理内存的机器上申请8G内存能成功吗?
问题来了:4GB物理内存的机器上申请8G内存能成功吗?
2022-07-21 13:56:00 【InfoQ】

正文
- 如果有,就直接分配物理内存,并建立虚拟内存与物理内存之间的映射关系。
- 如果没有空闲的物理内存,那么内核就会开始进行回收内存的工作,如果回收内存工作结束后,空闲的物理内存仍然无法满足此次物理内存的申请,那么内核就会放最后的大招了触发 OOM (Out of Memory)机制。

- 32 位系统的内核空间占用 1G,位于最高处,剩下的 3G 是用户空间;
- 64 位系统的内核空间和用户空间都是 128T,分别占据整个内存空间的最高和最低处,剩下的中间部分是未定义的。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main() {
int ret;
char* addr[4];
printf("使用cat /proc/%d/maps查看内存分配\n",getpid());
size_t s = 1024 * 1024 * 1024;
int i = 0;
for(i = 0; i < 4; ++i) {
printf("alloc size = %d\n", s);
addr[i] = (char*) malloc(s);
printf("主线程调用malloc后,申请1gb大小得内存,此内存起始地址:0X%x\n", addr[i]);
}
getchar();
return 0;
}

# ps aux | grep alloc_4g
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 7797 0.0 0.0 4198540 352 pts/1 S+ 16:58 0:00 ./alloc_4g
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main() {
int ret;
char* addr[4];
printf("使用cat /proc/%d/maps查看内存分配\n",getpid());
size_t s = 1024 * 1024 * 1024;
int i = 0;
for(i = 0; i < 4; ++i) {
printf("alloc size = %d\n", s);
addr[i] = (char*) malloc(s);
printf("主线程调用malloc后,申请1gb大小得内存,此内存起始地址:0X%x\n", addr[i]);
//访问虚拟内存
memset(addr[i], 0, s);
}
getchar();
return 0;
}

- 在 32 位操作系统,因为进程最大只能申请 3 GB 大小的虚拟内存,所以直接申请 8G 内存,会申请失败。
- 在 64位 位操作系统,因为进程最大只能申请 128 TB 大小的虚拟内存,即使物理内存只有 4GB,申请 8G 内存也是没问题,因为申请的内存是虚拟内存,等这块虚拟内存被访问了,因为物理空间不够,就会发生 OOM。
边栏推荐
猜你喜欢
[featured] expression package bucket map applet (drainage, traffic master, rights and interests take away CPS, with PC background management)
Judging whether a person is reliable depends on these three points
Explain soap Simple Object Access Protocol in detail
Openlayers:点聚合效果
Attack and defense world ---mfw
Ros2 learning notes: Launch script
数组双指针-刻意练习
Postman - post request application / x-www-from-urlencoded
高校重金引进23名菲律宾博士,有关部门已展开调查!
电脑是怎样上网的 (四) 局域网与服务器响应
随机推荐
China's mobile phones suffered a major setback for the first time, while Samsung and apple increased significantly
在代码评审中用好这7招,很容易就能建立起你的反对同盟
npm install 报 -4058错误
Judging whether a person is reliable depends on these three points
【英语口语】01 - 原子介绍
国家互联网信息办公室对滴滴全球股份有限公司依法作出网络安全审查相关行政处罚的决定
推荐系统之ROC和AUC详解
Document operation management
StringUtils 和 String 方法一览
Postman - post请求application/json参数
Matlab least square fitting
初步学习Oracle之PL/SQL
yii2的加密解密那些事儿
Map collection traversal in multiple ways
js 图片转换base64 base64转换为file对象
ES6 类的使用(class)
Virtual machine cannot connect to the Internet
聊聊接口设计的36个小技巧
Onvif协议及协议测试工具使用详解
D3.js + canvas drawing organization chart