Does mmap or malloc allocate RAM?

前端 未结 2 1817
有刺的猬
有刺的猬 2020-12-28 21:17

I know this is probably a stupid question but i\'ve been looking for awhile and can\'t find a definitive answer. If I use mmap or malloc (in C, on

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 21:53

    This is very OS/machine dependent.

    In most OSes neither allocates RAM. They both allocate VM space. They make a certain range of your processes virtual memory valid for use. RAM is normally allocated later by the OS on first write. Until then those allocations do not use RAM (aside from the page table that lists them as valid VM space).

    If you want to allocate physical RAM then you have to make each page (sysconf(_SC_PAGESIZE) gives you the system pagesize) dirty.

    In Linux you can see your VM mappings with all details in /proc/self/smaps. Rss is your resident set of that mapping (how much is resident in RAM), everything else that is dirty will have been swapped out. All non-dirty memory will be available for use, but won't exist until then.

    You can make all pages dirty with something like

    size_t mem_length;
    char (*my_memory)[sysconf(_SC_PAGESIZE)] = mmap(
          NULL
        , mem_length
        , PROT_READ | PROT_WRITE
        , MAP_PRIVATE | MAP_ANONYMOUS
        , -1
        , 0
        );
    
    int i;
    for (i = 0; i * sizeof(*my_memory) < mem_length; i++) {
        my_memory[i][0] = 1;
    }
    

    On some Implementations this can also be achieved by passing the MAP_POPULATE flag to mmap, but (depending on your system) it may just fail mmap with ENOMEM if you try to map more then you have RAM available.

提交回复
热议问题