2013-07-06 49 views
1

即使物理RAM小于3 GB,这个有趣的代码也总是在Linux系统中分配3 GB的内存。为什么这种内存分配的怪异行为

怎么样? (我在我的系统中的2.7 GB的RAM和该代码分配3.054 MB内存!)

#include <stdio.h> 
    #include <string.h> 
    #include <stdlib.h> 
    int main(int argc, char *argv[]) 
    { 
     void *ptr; 
     int n = 0; 
     while (1) { 
      // Allocate in 1 MB chunks 
      ptr = malloc(0x100000); 
      // Stop when we can't allocate any more 
      if (ptr == NULL) 
       break; 
      n++; 
     } 
     // How much did we get? 
     printf("malloced %d MB\n", n); 
     pause(); 
    } 
+0

您是否启用了交换文件/分区? – user2422531

+0

@ user2422531:我有,但我禁用了交换,但仍然得到了相同的结果。 – Inquisitive

+0

在OS下查找网络上的虚拟内存。 – 0decimal0

回答

1

默认情况下,在Linux中,在实际尝试修改它之前,实际上并没有获得RAM。你可能会尝试修改你的程序如下,看看它是否死亡越快:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
int main(int argc, char *argv[]) 
{ 
    char *ptr; 
    int n = 0; 
    while (1) { 
     // Allocate in 4kb chunks 
     ptr = malloc(0x1000); 
     // Stop when we can't allocate any more 
     if (ptr == NULL) 
      break; 
     *ptr = 1; // modify one byte on the page 
     n++; 
    } 
    // How much did we get? 
    printf("malloced %d MB\n", n/256); 
    pause(); 
} 

如果你有足够的交换,但RAM不足,那么这段代码将开始颠簸严重的交换文件。如果您的交换空间不足,它可能会在到达结尾之前崩溃。

正如其他人指出的那样,Linux是一种虚拟内存操作系统,当机器内存少于应用程序请求时,它将使用该磁盘作为后备存储。您可以使用的总空间是由三个方面的限制:

  • 分配掉
  • 虚拟地址空间的大小由ulimit
征收
  • 资源限制的内存和硬盘的组合量

    在32位Linux中,操作系统为每个任务提供3GB的虚拟地址空间来播放。在64位Linux中,我相信这个数字是100兆兆字节。不过,我不确定默认的ulimit是什么。因此,找到一个64位系统,并尝试修改后的程序。我想你会在一个漫长的夜晚。 ;-)

    编辑:这是默认值ulimit我64位的Ubuntu 11.04系统上:

    $ ulimit -a 
    core file size   (blocks, -c) 0 
    data seg size   (kbytes, -d) unlimited 
    scheduling priority    (-e) 20 
    file size    (blocks, -f) unlimited 
    pending signals     (-i) 16382 
    max locked memory  (kbytes, -l) 64 
    max memory size   (kbytes, -m) unlimited 
    open files      (-n) 1024 
    pipe size   (512 bytes, -p) 8 
    POSIX message queues  (bytes, -q) 819200 
    real-time priority    (-r) 0 
    stack size    (kbytes, -s) 8192 
    cpu time    (seconds, -t) unlimited 
    max user processes    (-u) unlimited 
    virtual memory   (kbytes, -v) unlimited 
    file locks      (-x) unlimited 
    

    所以,似乎没有对任务的默认内存大小限制。

  • 2

    当机器用完物理内存来解决他们可以使用的硬盘空间来“充当RAM”。这是显着的减少,但仍然可以完成。

    一般有几个层次机器可以用它来获取信息:

    1. 缓存(最快)
    2. RAM
    3. 硬盘(最慢)

    它会尽可能快地使用,但正如您指出的那样,有时需要使用其他资源。

    相关问题