c - Why this weird behaviour of memory allocation -


this interesting code allocates 3 gb memory in linux systems if physical ram less 3 gb.

how? (i have 2.7 gb ram in system , code allocated 3.054 mb memory!)

    #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 can't allocate more             if (ptr == null)                 break;             n++;         }         // how did get?         printf("malloced %d mb\n", n);         pause();     } 

by default in linux, don't ram until try modify it. might try modifying program follows , see if dies sooner:

#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 can't allocate more         if (ptr == null)             break;         *ptr = 1;  // modify 1 byte on page         n++;     }     // how did get?     printf("malloced %d mb\n", n / 256);     pause(); } 

if have sufficient swap insufficient ram, code start thrashing swapfile heavily. if have insufficient swap, may crash before reaches end.

as else pointed out, linux virtual memory operating system , use disk backing store when machine has less ram application requests. total space can use limited 3 things:

  • the combined amount of ram , disk allocated swap
  • the size of virtual address space
  • resource limits imposed ulimit

in 32-bit linux, os gives each task 3gb virtual address space play with. in 64-bit linux, believe number in 100s of terabytes. i'm not sure default ulimit is, though. so, find 64-bit system , try modified program on that. think you'll in long night. ;-)

edit: here's default ulimit values on 64-bit ubuntu 11.04 system:

$ 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 

so, appears there isn't default memory size limit task.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -