Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many GB can malloc allocate for your program

I used the following code to find it out but I always get 1 as the answer. is there something wrong. Thanks

#include <stdio.h>
#include <stdlib.h>

int main(){
    int mult = 0;
    int chk =8;
    do{
        mult+=1;
        int *p = (int*)malloc(1024*1024*1024*mult);
        if(p==0){
            chk =0;

        }else{
            free(p);
        }
    }while(chk !=0);
    mult = mult -1;
    printf("The number of gigs allocated is : %d\n",mult);
    return 0;
}

Just to help, I have a 64 bit system with both windows and linux installed. Thus, is the above logic correct even though I am getting just 1 gb as the answer on a 64 bit system?

like image 364
user465983 Avatar asked Feb 02 '11 16:02

user465983


People also ask

How many bytes does malloc 10 allocate?

malloc(10) allocates 10 bytes, which is enough space for 10 chars. To allocate space for 10 ints, you could call malloc(10 * sizeof(int)) . char *cp = malloc(10); int *ip = malloc(sizeof(int));

Can malloc allocate more memory than RAM?

Malloc allocates memory more than RAM.

How many bytes will malloc 4 allocate?

The malloc line allocates a block of memory of the size specified -- in this case, sizeof(int) bytes (4 bytes). The sizeof command in C returns the size, in bytes, of any type. The code could just as easily have said malloc(4), since sizeof(int) equals 4 bytes on most machines.

Does malloc allocate in bytes?

The malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of the space that's required for alignment and maintenance information.


2 Answers

If it is a 32-bit OS, then it is not surprising that the largest contiguous block would be 1GB (or somewhere between that and 2GB). On a 64-bit OS, larger blocks would be possible.

If you change your code to allocate smaller individual pieces, you will likely be able to allocate more than 1GB total.

like image 111
Mark Wilkins Avatar answered Oct 11 '22 23:10

Mark Wilkins


These questions might help you a bit: How much memory was actually allocated from heap for an object? and How do I find out how much free memory is left in GNU C++ on Linux

like image 21
jwir3 Avatar answered Oct 12 '22 00:10

jwir3