Why malloc doesn't allocate memory until I hit a certain threshold?

前端 未结 2 707
死守一世寂寞
死守一世寂寞 2021-01-15 12:20
#include 
#include 
#include 

int main(int argc, char *argv[])
{
        size_t sz = atol(argv[1]);
        char *arr         


        
2条回答
  •  梦毁少年i
    2021-01-15 13:01

    What you're seeing in the pmap output is almost certainly the addition needed to the malloc arena to satisfy larger requests, not any single request.

    The arena is the pool of memory from which allocations are handed out and there's a good chance this starts at a certain size and is only expanded on demand.

    For example, if the initial arena is 1000K, any allocation that does not exhaust that will have no need to get extra arena space. If you do exhaust that space, the process will try to request more arena from the underlying environment so it can satisfy the extra demand.


    As to why the size isn't what you requested, there are (at least) two possible reasons. First, the arena isn't just the memory allocated for your purposes, it also holds control information so that the memory can be properly managed (sizes, checksums, pointers, free list and so on).

    Secondly, malloc may over-allocate on the expectation that this won't be the last request that exhausts the current arena. Some memory allocation strategies go so far as to double the current arena size when requesting more, in order to amortise the cost of doing so.

提交回复
热议问题