Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - wanted to know max memory allocable size in a program

Tags:

c

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, total);
        if (v == NULL) break;
    }
} 

Edit: running this program on CentOS 5.4 64 bit.

like image 495
allenhwkim Avatar asked Jul 31 '26 17:07

allenhwkim


2 Answers

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!

like image 140
strager Avatar answered Aug 02 '26 08:08

strager


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.

like image 36
ta.speot.is Avatar answered Aug 02 '26 10:08

ta.speot.is