C - wanted to know max memory allocable size in a program
I am a newbee in C
I wanted to know the max memory allowed by an application. So I wrote a little program like the following.
I have a machine with 16GB total memory and 2GB is used and 14GB is free. I expected this program to stop around 14GB, but it runs forever.
Want am I doing wrong here?
#include <stdlib.h>
#include <stdio.h>
int main(){
long total = 0;
void* v = malloc(1024768);
while(1) {
total += 1024768;
printf ( "Total Memory allocated : %5.1f GB\n", (float)total/(1024*1024768) );
v = realloc(v开发者_Python百科, total);
if (v == NULL) break;
}
}
Edit: running this program on CentOS 5.4 64 bit.
On most modern operating systems, memory is allocated for each page which is used, not for each page which is "reserved". Your code doesn't use any pages, so no memory is really allocated.
Try clearing the memory you allocate with memset
; eventually the program will crash because it can no longer allocate a page.
I tried to find a citation for this, but I was unsuccessful. Help with this is appreciated!
Want am I doing wrong here?
Well you say that the machine you are running the application on has 16GB of RAM, so I'm going to assume it's 64-bit. This means that your application will run for ages before it exhausts 1/ the physical memory and 2/ the virtual memory.
On 32-bit Windows your application would stop at 4GB. On 64-bit Windows your application will stop at 16TB (assuming you have a page file that can grow automatically, and that much hard disk space).
http://support.microsoft.com/kb/294418
YMMV with other operating systems.
Edit: ruslik points out that in practice, your process will not be able to allocate memory up to 2GB or 3GB (depending on how your binary is compiled) on 32-bit Windows. From the KB article I link above, the maximum memory that your process will occupy is 3GB or 4GB, with 1GB belonging to the OS that you can't use.
If you're on one specific platform/OS, you should use report functions, spectific to that OS.
If you're eritiong cross-platform program, you shouldn't rely on any free memory checking algorithm. Reasons are:
- OS may refuse to give all available memory due to own reasons: fragmentation, alloc limits or so.
- OS may not really give a memory, just allocate the space if it have VMM.
- Algorithm may change internal state of MM, so memory available before and after call to check may be different.
- As OS runs several processes in parallel, available memory may be changed sponteneously due to other process activity.
精彩评论