Search code examples
ccalloc

How do I calculate beforehand how much memory calloc would allocate?


I basically have this piece of code.

char (* text)[1][80];
text = calloc(2821522,80);

The way I calculated it, that calloc should have allocated 215.265045 megabytes of RAM, however, the program in the end exceeded that number and allocated nearly 700mb of ram.

So it appears I cannot properly know how much memory that function will allocate.

How does one calculate that propery?


Solution

  • calloc (and malloc for that matter) is free to allocate as much space as it needs to satisfy the request.

    So, no, you cannot tell in advance how much it will actually give you, you can only assume that it's given you the amount you asked for.

    Having said that, 700M seems a little excessive so I'd be investigating whether the calloc was solely responsible for that by, for example, a program that only does the calloc and nothing more.

    You might also want to investigate how you're measuring that memory usage.

    For example, the following program:

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    
    int main (void) {
        char (* text)[1][80];
        struct mallinfo mi;
    
        mi = mallinfo(); printf ("%d\n", mi.uordblks);
        text = calloc(2821522,80);
        mi = mallinfo(); printf ("%d\n", mi.uordblks);
    
        return 0;
    }
    

    outputs, on my system:

    66144
    225903256
    

    meaning that the calloc has allocated 225,837,112 bytes which is only a smidgeon (115,352 bytes or 0.05%) above the requested 225,721,760.