开发者

How many GB can malloc allocate for your program

开发者 https://www.devze.com 2023-02-07 23:05 出处:网络
I used the following code to find it out but I always get 1 as the answer. is there something wron开发者_StackOverflow社区g. Thanks

I used the following code to find it out but I always get 1 as the answer. is there something wron开发者_StackOverflow社区g. 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?


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.


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


int main(void){
    int MB = 0;
    while(malloc(1<<30)){
        ++MB;
    }
    printf("The number of gigs allocated is : %d\n",MB);
    return EXIT_SUCCESS;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消