maximum memory which malloc can allocate

2019-01-03 09:36发布

I was trying to figure out how much memory I can malloc to maximum extent on my machine (1 Gb RAM 160 Gb HD Windows platform).

I read that the maximum memory malloc can allocate is limited to physical memory (on heap).

Also when a program exceeds consumption of memory to a certain level, the computer stops working because other applications do not get enough memory that they require.

So to confirm, I wrote a small program in C:

int main(){  
    int *p;
    while(1){
        p=(int *)malloc(4);
        if(!p)break;
    }   
}

I was hoping that there would be a time when memory allocation would fail and the loop would break, but my computer hung as it was an infinite loop.

I waited for about an hour and finally I had to force shut down my computer.

Some questions:

  • Does malloc allocate memory from HD also?
  • What was the reason for above behaviour?
  • Why didn't loop break at any point of time?
  • Why wasn't there any allocation failure?

7条回答
Melony?
2楼-- · 2019-01-03 10:23

malloc does its own memory management, managing small memory blocks itself, but ultimately it uses the Win32 Heap functions to allocate memory. You can think of malloc as a "memory reseller".

The windows memory subsystem comprises physical memory (RAM) and virtual memory (HD). When physical memory becomes scarce, some of the pages can be copied from physical memory to virtual memory on the hard drive. Windows does this transparently.

By default, Virtual Memory is enabled and will consume the available space on the HD. So, your test will continue running until it has either allocated the full amount of virtual memory for the process (2GB on 32-bit windows) or filled the hard disk.

查看更多
登录 后发表回答