为什么没有malloc的填充内存? [英] Why isn't malloc filling up memory?

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

问题描述

我有以下的code:

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

int main() {
    int data = 0;
    char *byte = (char *)malloc(sizeof(char)*1000000000);
byte[999999999] = 'a';
printf("%c",byte[999999999]);
    scanf("%d",&data);
    return 0;
}

在内存中寻找程序启动和scanf函数之前,我会期望内存增加1 GB之前。为什么不是这样?

Looking at memory before the program starts and before the scanf I would expect the memory to increase of 1 GB. Why isn't this happening?

编辑:我添加

byte[999999999] = 'a';
printf("%c",byte[999999999]);

程序输出 A

推荐答案

默认情况下,Linux的懒洋洋地分配物理内存,它访问的第一次。您对的malloc 通话将分配虚拟内存块大,但也有尚未映射到它的物理内存的任意页面。到未映射页第一访问将导致故障,这内核将通过分配和映射的物理存储器中的一个或多个页面处理

By default, Linux allocates physical memory lazily, the first time it's accessed. Your call to malloc will allocate a large block of virtual memory, but there are not yet any pages of physical memory mapped to it. The first access to an unmapped page will cause a fault, which the kernel will handle by allocating and mapping one or more pages of physical memory.

要分配所有的物理内存,你必须在每一页上访问至少一个字节;或者你可以绕过的malloc 键,直接进入操作系统的东西像

To allocate all the physical memory, you'll have to access at least one byte on every page; or you could bypass malloc and go straight to the operating system with something like

mmap(0, 1000000000, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);

请注意使用 MAP_POPULATE 的填充页表,即立即分配物理内存。根据该手册页,这仅适用于相当新版本的Linux。

Note the use of MAP_POPULATE to populate the page tables, i.e. to allocate physical memory, immediately. According to the manpage, this only works on fairly recent versions of Linux.

这篇关于为什么没有malloc的填充内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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